Javascript TagName

时间:2015-11-12 11:38:53

标签: javascript

Is it possible to get a TagName that is below a TagName.

For example:

<strong><em>Test</em></strong>
<em>Test2</em>

Is it possible to only get the tag in the tag? In other words, only the Test elements should be returned.

The most I can figure out is var x = document.getElementsByTagName("strong") and I want something along the lines of x = x.getElementsByTagName("em"). (I have practically no js experience)

Limitations: I am using Confluence so I am unable to to change the html i.e. no ID's/classes for these elements.

6 个答案:

答案 0 :(得分:2)

If you want to use vanilla JS, you can use something like this:

document.querySelectorAll('strong em')

You can get more information about CSS selectors here.

答案 1 :(得分:1)

PURE JS SOLOUTION

You will probably need to parse more than one tag. For this situation you can use something like this.

//get all "em" elements
var elements = document.getElementsByTagName("em");
//prepare final array
var tags = [];

//go throught every "em" element
for(var index in elements) { 
   if (elements.hasOwnProperty(index)) {
       //check if element parent is <STRONG>
       if(elements[index].parentNode.nodeName == 'STRONG'){
        tags.push(elements[index].innerHTML)
       }
   }
}

//final array with tags
console.log(tags);

This will return all tags from string with pattern <strong><em>Tag</em></strong>

For example, if you have this HTML

<strong><em>Test</em></strong>
<em>Test2</em><strong><em>Test2</em></strong>
<em>Test2</em><strong><em>Test3</em></strong>
<em>Test2</em><strong><em>Test4</em></strong>
<em>Test2</em><strong><em>Test5</em></strong>
<em>Test2</em><strong><em>Test6</em></strong>
<em>Test2</em><strong><em>Test7</em></strong>
<em>Test2</em><strong><em>Test8</em></strong>
<em>Test2</em><strong><em>Test9</em></strong>
<em>Test2</em><strong><em>Test10</em></strong>

Output will be:

["Test", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7", "Test8", "Test9", "Test10"]

答案 2 :(得分:0)

document.getElementsByTagName("strong") will return you a collection of items, so to call it again, you need to actually call it on an item of that collection, like x[0].getElementsByTagName("em"). So you'll need to loop all the elements of x and execute on each of them getElementsByTagName and collect all the children in an array.

答案 3 :(得分:0)

since document.getElementsByTagName will give array what you need is index 0

console.log(document.getElementsByTagName("em")[0].innerHTML);
<strong><em>Test</em></strong>
<em>Test2</em>

答案 4 :(得分:0)

You could use the following:

var elements = document.querySelectorAll('strong em');
console.log(elements);

This will return only ems which are under strong tag

You could use also class selectors too like:

var elements = document.querySelectorAll('strong em.myclass');

答案 5 :(得分:-1)

You could use query selector like this:

If you use jQuery

$("strong em");

Otherwise:

document.querySelectorAll("strong em");