Is there a way to get elements by specific values

984 Views Asked by At

I am trying to code a toggler that will show/hide all of the content on any given page that has a specific tag. The problem I am facing is that I cannot figure out how to identify the elements.

The web pages are created using a program called MadCap Flare. In Flare, you can add Conditional Text Tags to elements that help determine what is and isn't built (among other things). In the final HTML output, these Conditional Text Tag are still present. So a paragraph with a Conditional Text Tag called MyTag would show as:

<p data-mc-conditions="MyTag">Here is my paragraph text.</p>

Given that these Conditional Text Tags are native to Flare, I am trying to find a way to identify all elements with specific Conditional Text Tags.

I looked at GetElementByID, GetElementsByTagName, GetElementsByClassName, and was hoping there was something similar to query and find all elements with a given Conditional Text Tag.

1

There are 1 best solutions below

7
AudioBubble On

You can use a combination of CSS selectors and for this:
document.querySelector("p[data-mc-conditions='MyTag']");

document.querySelector("p[data-mc-conditions='MyTag']").style.border = "5px solid yellow";
<p data-mc-conditions="MyTag">Here is my paragraph text.</p>

The querySelector is described by w3schools.com:

The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.

However, you probably have multiple elements and, therefore, you want to use
querySelectorAll().
But you will have to loop through the elements individually:

var elements = document.querySelectorAll("p[data-mc-conditions='MyTag']");

for (var i = 0; i < elements.length; i++) {
  elements[i].style.border = "5px solid yellow";
}
<p data-mc-conditions="MyTag">Here is my paragraph text.</p>
<p data-mc-conditions="MyTag">Here is my paragraph text.</p>
<p data-mc-conditions="MyTag">Here is my paragraph text.</p>
<p data-mc-conditions="MyTag">Here is my paragraph text.</p>