The Ultimate Guide To JavaScript Dom Manipulation With Practice Project

Здравствуйте,
В разработке веб-сайтов DOM означает Document Object Model. Манипуляция DOM — это когда вы используете JavaScript для добавления, удаления и изменения элементов веб-сайта. И в этом уроке вы узнаете, как это сделать. В конце я дам ссылку на GitHub на практический проект, который вам стоит проверить.
Мы не будем рассматривать события, обработчики событий и различные способы доступа к элементам и манипулирования ими. Но мы рассмотрим рекомендуемый и простой способ.

Доступ к элементам Dom

Так же, как вы выбираете элементы с помощью CSS.

// Returns the first element within the document that matches the specified group of selector/selectors. 
//Now you have also access to the element attributes, element.href etc and you can directly change any property element.href = "https://newlink.com"
const element = document.querySelector('.someclass')
// Returns a list of the elements within the document using depth-first pre-order traversal of the document's node. That match the specified group of selector/selectors.
const eleList = document.querySelectorAll('.someclass')
// Getting child nodes
const getIt = document.querySelector('.someclass')
const children = getIt.childNodes
// Getting parent node
const parent = children.parentNode
//A few others you can use
//element.previousSibling
//element.nextSibling
//element.firstChild
//element.lastChild
Вход в полноэкранный режим Выход из полноэкранного режима

Создание новых элементов DOM

//create h1 element
const heading = document.createElement('h1');
// create a text node for the element
const headingText= document.createTextNode('This is the h1 heading!');
// Attach the text node to the element
heading.appendChild(headingText);
//Append the element to the body or to a specific element
document.body.appendChild(heading)
element.appendChild(heading)
Войти в полноэкранный режим Выход из полноэкранного режима

Выбор элемента, добавление содержимого, замена и удаление элементов

//Select the element
const element = document.querySelector('.someclass')
//Get the inner text , innerText or just using the text
const insideText = element.innerText
//Adding more content to element
element.innerText = insideText + "the new value"
//Replacing the value
element.innerText = "New Value"
//Use innerHTML if you want to add HTML along with it
element.innerHTML = "New Heading Value <a href="https://dev.to/itsfz1">Developer</a>"
//Let's remove this element from the dom tree
element.remove()
Войти в полноэкранный режим Выход из полноэкранного режима

Вставка HTML в разных местах

const element = document.querySelector('.someclass')
// beforebegin - The HTML would be placed immediately before the element, as a sibling.
// afterbegin - The HTML would be placed inside the element, before its first child.
// beforeend - The HTML would be placed inside the element, after its last child.
// afterend - The HTML would be placed immediately after the element, as a sibling.
element.insertAdjacentHTML("afterbegin
", "<div><p>New Grid Item</p></div>");
Вход в полноэкранный режим Выход из полноэкранного режима

Добавление, удаление, переключение, проверка классов

const element = document.querySelector('.someclass')
// Will remove unwanted if it is a class of element
element.classList.remove("unwanted");
//Will add the class 'anotherClass' if one does not already exist
element.classList.add("anotherclass");
// Add or remove multiple classes
element.classList.add("class1", "class2");
element.classList.remove("c1", "c2");
//If "visible" class is set remove it, otherwise add it
element.classList.toggle("visible");
// will return true if it has class of 'exist' or false if it does not
const flag = element.classList.contains("exist");
flag ? "Yes this class exist" : "Not exist"
Войти в полноэкранный режим Выход из полноэкранного режима

Получение, добавление и удаление атрибутов

const element = document.querySelector('.someclass')
//will return the link
element.getAttribute("href")
//will set class="awsome"
element.setAttribute("class", "awsome")
//Will remove the attribute from element
element.removeAttribute("class")
//Check for attribute existance, it returns a boolean
if (element.hasAttribute("target")) {
    element.setAttribute("style", "color: green; text-decoration: none;");
  }
Войти в полноэкранный режим Выход из полноэкранного режима

Вот ссылка на практический проект.

Бонус

Вы можете назначить несколько атрибутов без использования нескольких функций setAttribute за один раз, как показано здесь:

const elementInput = document.createElement("input")
 Object.assign(elementInput , {
        className: "textField",
        id: "address",
        name: "address",
        type: "text",
        placeholder: "",
        value: ""
    })
document.body.appendChild(elementInput )
Войти в полноэкранный режим Выйти из полноэкранного режима

Разница между «innerText» и «textContent» в том, что innerText возвращает только видимый текст без интервалов, а textContent возвращает видимый и невидимый текст, включая скрипт с интервалами.
Спасибо за чтение!

Оцените статью
devanswers.ru
Добавить комментарий