Selectors are those methods that allow us to find and select tags within the DOM to obtain their values and content within an html page.
In the following example, if we have a "div" tag inside the DOM with an "id" whose value is "myid", through the selectors we can collect the value and content of that tag.
To use the selectors we create a script at the end of the body, and within that script we will create a "contentDiv" variable, this variable will make use of the "document" object, which will allow us to access the html tags within the document through selectors.
<html>
<head>
<title>My title</title>
</head>
<body>
<div id="myid">This is my id</div>
<script type="text/javascript">
var contentDiv = document.getElementById("myid");
console-log(contentDiv.innerText);
var contentDiv2 = document.getElementsByTagName("div");
console-log(contentDiv2);
</script>
</body>
<html>
We have the following basic selectors:
document.querySelector(".contentValue");
document.querySelector("#contentValue");
Example:var contentDiv2 = document.getElementsByTagName("div");
contentDiv2[0].id = "value id";
In this example we collect all the div inside the DOM through the getElementsByTagName selector inside an array type variable called "contentDiv2",
then access its position 0 and add an id through "contentDiv2[0].id" with value "value id".
From the browser inspector we can see this better, the html result would be:
<div id="value id"></div>
var contentDiv2 = document.getElementsByTagName("div");
contentDiv2[0].style.backgroundColor = "red";
Which would give us a red background color for "<div id="value id"></div>
".
<ul id="myul"></ul>
We have the script:var content_ul = document.querySelector("#myul");
var li = document.createElement('li');
content_ul.appendChild(li);
console.log(content_ul);
Example, we remove the "li" tag that is inside "ul":
Starting from the html code:<ul id="myul"><li></li></ul>
We have the script:var selectedElement = document.getElementById("myul");
var selectedElementLi = document.getElementById("myli");
selectedElement.removeChild(selectedElementLi);
console.log(selectedElement);
Tips on SEO and Online Business
Next Articles
Previous Articles