1

I want to target a specified div, but my example for now is only when it has an id. I want to use pure Javascript

current:

<div id="my_id">hello</div>

<script>
document.getElementById('my_id').insertAdjacentHTML('beforebegin',
    '<h3>text</h3>');
</script>

my case:

<div data-foo="bar">hello</div>
<div data-foo="club">hi</div>

How can I target the div that has the bar data-foo attribute ?

1 Answer 1

1

You can do this using an attribute selector alongside querySelector:

document.querySelector("div[data-foo='bar']").insertAdjacentHTML('beforebegin',
'<h3>text</h3>');
<div data-foo="bar">hello</div>
<div data-foo="club">hi</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.