javascripthtmljqueryattributes

Getting one data attribute using another


See the DIV below. If I store the data=value attribute "?=url=homepage" in a variable, how can I use it to find the corresponding data-target attribute in the same DIV? There would be a lot of different DIVs but they will all have a unique data-target and data-value that go together. I imagine I can use javascript or jquery to accomplish this.

<header>
<div id="nav" title="Homepage" data-target="practice-page-1.php" data-value="?url=homepage">Homepage</div>
</header>

Solution

  • You can use a css selector to locate the element with the matching "data-value" attribute. Here's a quick demo

    let dv = "?url=homepage";
    
    let el = document.querySelector(`[data-value='${dv}']`);
    
    if (el) {
      console.log(el.dataset.target);
    } else {
      console.log("not found");
    }
    <header>
    <div id="nav" title="Homepage" data-target="practice-page-1.php" data-value="?url=homepage">Homepage</div>
    </header>