+ 10
Select through js
In the code below how can I select all span tag using JAVASCRIPT just like CSS " p span {//codes} ". Note: not using any class name or id. https://code.sololearn.com/W9vHIyf0VbVg/?ref=app
15 ответов
+ 6
If you won't to do "css like selection" from JS then querySelector & querySelectorAll are the best options I would suggest you.
+ 4
it will get all the span within #cont Container and change the background color of 3rd span element
https://code.sololearn.com/Whc3UwXYjZWe/?ref=app
+ 3
document.getElementsByTagName("span");
+ 3
Artur in the question he has mentioned to select all span, so I used map to change the background color, of all element..
And then later in the comment he said to target single element of that span, so I just added if condition to same code
+ 3
TRY THIS
document.querySelector('p span');
+ 2
Artur no, I know this one... something else like in CSS div p{}
edit: what if I want to select span in third p tag. We can do ....tagName("span")[3], something like this.. but when the code is 1000 lines code, there is a chance of having a lot of p or span tag..in this case we don't know the correct index of the element.
There may be a alternative way for this,. I'm finding that.
+ 2
Artur Check the edit.
+ 2
Artur K@$hy@p~Kum@r®™[✓] ya we need to work with index, BUT that index we definitely know because it is in #cont container, and that being unique, we know the element position..
Even in css we use nth-child or the even odd pseudo classes so that we can target specific child element which are repeating.. there as well we provide the index..
The sole purpose of id and classes are to distinguish elements and categorise them with similar classes.. so we need to use them
If not so, then to target a specific element just by tags are not easy.
Edit:
For ex :
<div>
<p>Para from div 1</p>
<p>Para from div 2</div>
</div>
<div>
<p>Para from div 2</p>
<p>Para from div 2</div>
</div>
<div>
<p>Para from div 3</p>
<p>Para from div 3</div>
</div>
How can we target the second div paragraph 2?
either by index, or ID and classes.
+ 2
Use
document.querySelectorAll(span)
+ 1
You mean you want to get all p tags inside div tag?
+ 1
element.getElementsByTagName(" ");
"element" - is the element from where the search starts. Only the element's descendants are included, not the element itself.
+ 1
Мг. Кнап🌠 you still have to work with index in your if statement in map method
+ 1
why would you use map method, spread and all that stuff if you can get the same result using querySelector. I don't get it
+ 1
May be I don't understand something, idk