Как найти элемент по href js

2016 update

It’s been over 4 years since this question was posted and things progressed quite a bit.

You can’t use:

var els = document.getElementsByTagName("a[href='http://domain.example']");

but what you can use is:

var els = document.querySelectorAll("a[href='http://domain.example']");

(Note: see below for browser support)

which would make the code from your question work exactly as you expect:

for (var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  el.innerHTML = el.innerHTML.replace(/link1/gi, 'dead link');
}

You can even use selectors like a[href^='http://domain.example'] if you want all links that start with 'http://domain.example':

var els = document.querySelectorAll("a[href^='http://domain.example']");

for (var i = 0, l = els.length; i < l; i++) {
  var el = els[i];
  el.innerHTML = el.innerHTML.replace(/link/gi, 'dead link');
}

See: DEMO

Browser support

The browser support according to Can I use as of June 2016
looks pretty good:

caniuse.com/queryselector
(See: http://caniuse.com/queryselector for up to date info)

There is no support in IE6 and IE7 but
IE6 is already dead
and IE7 soon will be with its 0.68% market share.

IE8 is over 7 years old and it partially supports querySelectorAll – by “partially” I mean that you can use CSS 2.1 selectors like [attr], [attr="val"], [attr~="val"], [attr|="bar"] and a small subset of CSS 3 selectors which luckily include:
[attr^=val], [attr$=val], and [attr*=val] so it seems that IE8 is fine with my examples above.

IE9, IE10 and IE11 all support querySelectorAll with no problems, as do Chrome, Firefox, Safari, Opera and all other major browser – both desktop and mobile.

In other words, it seems that we can safely start to use querySelectorAll in production.

More info

For more info, see:

  • https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
  • https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
  • http://caniuse.com/queryselector

See also this answer for the difference between querySelectorAll, querySelector, queryAll and query and when they were removed from the DOM specification.

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The task is to select the <a> element by its href attribute. A few of the techniques are discussed below. Here we are going to use JQuery to solve the problem. 

    Approach: Use JQuery selector $(‘a[href=link_to_site]’).

    Example 1: This example using the approach discussed above. 

    html

    </script>

    <h1 id="h1" style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP" style="font-size: 15px; font-weight: bold;">

    </p>

    </a>

    <br>

    <br>

    <button onclick="gfg_Run()">

        Click here

    </button>

    <p id="GFG_DOWN" style="font-size: 23px;

        font-weight: bold; color: green; ">

    </p>

    <script>

        var el_up = document.getElementById("GFG_UP");

        var el_down = document.getElementById("GFG_DOWN");

        el_up.innerHTML =

        "Click on the button to select the element by HREF attribute.";

        function gfg_Run() {

            el_down.innerHTML =

        }        

    </script>

    Output:

    How to get an element by its href attribute ?

    How to get an element by its href attribute ?

    Approach 2: Use JQuery selector $(‘a[href*=part_of_link]’). it will select the element if any part of the attribute matches with value.

    Example 2: This example using the approach discussed above. 

    html

    </script>

    <h1 id="h1" style="color:green;">

        GeeksforGeeks

    </h1>

    <p id="GFG_UP" style="font-size: 15px; font-weight: bold;">

    </p>

    </a>

    <br>

    <br>

    <button onclick="gfg_Run()">

        Click here

    </button>

    <p id="GFG_DOWN" style="font-size: 23px;

            font-weight: bold; color: green; ">

    </p>

    <script>

        var el_up = document.getElementById("GFG_UP");

        var el_down = document.getElementById("GFG_DOWN");

        el_up.innerHTML =

        "Click on the button to select the element by HREF attribute.";

        function gfg_Run() {

            el_down.innerHTML = $('a[href*="geeks.org"]').text();

        }        

    </script>

    Output:

    How to get an element by its href attribute ?

    How to get an element by its href attribute ?

    Last Updated :
    23 Jan, 2023

    Like Article

    Save Article

    Hello guys,  today we will learn about how to get an element by Href attribute using JavaScript in two different ways: Using the querySelector() method and getElementById(). Read the following article and then discuss this topic together.

    Using the querySelector() method

    The first way we want to introduce in this article is the querySelector() method. This method will return the matched elements as a CSS selector, and it will throw return an error if the selector is not matched.

    Syntax:

    document.querySelector(CSS selectors)

    Parameter: One or more CSS selectors. If you have multiple selectors, separate each selector with a comma.

    Return value: The return value is a NodeList.

    Code example:

    In this example, we use the querySelector() method with the href attribute. Let’s see the code below to get more information.

    <!DOCTYPE html>
    <html lang="en">
      <body>
        <h1 id="header"></h1>
        <a id="home" href="https://learnshareit.com/">LearnShareIT</a>
        <script src="script.js"></script>
      </body>
    </html>
    // Using the querySelector() method with href attribute
    var element = document.querySelector('[href*="learnshareit.com"]').href;
    console.log("The element is: ", element)

    Output

    The element is
    https://learnshareit.com/

    Using the getElementById() method

    The next way is the getElementById() method. The getElementById() method returns an element with a specified value and will return null if the element does not exist in the tag. We already explained how to use the getElement in this article. You can read it to get more information about this method.

    Syntax:

    document.getElementById(id)

    Parameter:

    • id: the id value of an element.

    Return value: the return value is the element with a specified id, and otherways will return null.

    Example:

    In this example, we call the getElementById() method to get the element and call the href attribute to get the href attribute. Let’s see the code example below.

    Index.html

    <!DOCTYPE html>
    <html lang="en">
      <body>
        <h1 id="header"></h1>
        <a id="home" href="https://learnshareit.com/">LearnShareIT</a>
        <script src="script.js"></script>
      </body>
    </html>

    Script.js

    // Using the getElementById() method with href attribute
    var element = document.getElementById("home").href;
    console.log("The element is: ", element)

    Output

    The element is: 
    https://learnshareit.com/

    Summary

    Through this article, we hope you know how to get an element by Href attribute using JavaScript. We have explained two methods in this article, but we think the solutions using the querySelector() method is useful and easy to use.

    Have a nice day, and leave your comment here if you have any questions!

    Maybe you are interested:

    • Remove the ID attribute from an Element using JavaScript
    • Create an Element with Style attribute in JavaScript
    • Solution To Create An Element With ID Attribute Using JS

    Fred Hall

    My name is Fred Hall. My hobby is studying programming languages, which I would like to share with you. Please do not hesitate to contact me if you are having problems learning the computer languages Java, JavaScript, C, C#, Perl, or Python. I will respond to all of your inquiries.


    Name of the university: HUSC
    Major: IT
    Programming Languages: Java, JavaScript, C , C#, Perl, Python

    Привет, коллеги!
    Подскажите как найти ссылку по тексту в href с помощью JS

    Вот ссылка:
    https://www.instagram.com/p/dfhgfgdfgdfgdgf/liked_by/

    нужно кликнуть по ней, найти ее нужно по совпадению “liked_by”

    Спасибо, за помощь


    • Вопрос задан

      более трёх лет назад

    • 2446 просмотров

    document.querySelector('a[href*="liked_by"]').click()

    const search = 'liked_by';
    const elem = Array.from(document.querySelectorAll('a')).find(
        el=>el.href.includes(search)
    );
    if(elem) elem.click();

    Пригласить эксперта


    • Показать ещё
      Загружается…

    15 мая 2023, в 23:34

    500 руб./за проект

    15 мая 2023, в 23:33

    1500 руб./за проект

    15 мая 2023, в 23:26

    1500 руб./за проект

    Минуточку внимания

    In CSS, selectors are patterns used to select the element(s) you want to style, but as you can tell from the title above, selectors are also useful in javascript and below are some examples on how to use them.

    Basics

    Using a selector in javascript

    • Use the .querySelector method
    const div = document.querySelector("div") // => First occurence of a div element in the document
    
    const p = div.querySelector("p") // => First occurence of a p element in the div
    
    

    Enter fullscreen mode

    Exit fullscreen mode

    • To get all matching elements, use the document.querySelectorAll method
    document.querySelectorAll("div") // NodeList of all div elements
    

    Enter fullscreen mode

    Exit fullscreen mode

    By IDs

    To get an element by its ID, use a # before the element ID

    document.querySelector("#id") // => document.getElementById('id')
    

    Enter fullscreen mode

    Exit fullscreen mode

    By classes

    To get elements by class, use a . before the class name

    document.querySelectorAll(".myElementClass")
    

    Enter fullscreen mode

    Exit fullscreen mode

    By tag name

    To get elements by tag name, just input the tag name

    document.querySelectorAll("body") // => document.getElementsByTagName('body')
    

    Enter fullscreen mode

    Exit fullscreen mode

    Replicating .getElementById and getElementsByTagName

    • Replicating .getElementById
    document.querySelector("#myDivId") // => document.getElementById('myDivId')
    

    Enter fullscreen mode

    Exit fullscreen mode

    • Replicating .getElementsByTagName
    document.querySelectorAll("a") // => document.getElementsByTagName('a')
    

    Enter fullscreen mode

    Exit fullscreen mode

    All elements

    To get all elements use *

    document.querySelectorAll("*") // => NodeList[...]
    

    Enter fullscreen mode

    Exit fullscreen mode

    Using multiple selectors

    To use multiple selectors, we seperate each of them with a ,.

    <html>
        <body>
            <p>Hello i am a paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelectorAll("p, a") // => NodeList[p,a,a]
    

    Enter fullscreen mode

    Exit fullscreen mode

    More with elements

    In the above examples, we made basic queries, but other things can be done like getting elements by order or parent.

    Getting element children

    There are two variants of this, one gets an element’s child no matter how deep it is down the tree, and the other gets an element’s direct child.

    <html>
        <body>
            <p>Hello i am a paragraph</p>
            <div>
                <a href="https://awesomeplace.com">Hey I am a link</a>
                <p>
                    Hello i am a paragraph and here's
                    <a href="https://anotherplace.com">a link</a>
                </p>
            </div>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    With the above HTML as an example, we will look at these two variants.

    • Direct child
    document.querySelector("div > a") // => <a href="https://awesomeplace.com">Hey I am a link</a>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • All children
    document.querySelectorAll("div a") // => NodeList[a,a]
    

    Enter fullscreen mode

    Exit fullscreen mode

    Getting elements by order

    There are two ways to do this also. Consider the following HTML.

    <html>
        <body>
            <div>
                <a href="https://awesomeplace.com">Hey I am a link</a>
                <pre>I should intervene but i wont</pre>
                <p>Hello i am another paragraph</p>
            </div>
            <p>Hello i am a paragraph</p>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • Placed after
    document.querySelector("div + p") // => <p>Hello i am a paragraph</p>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • Preceded by

    With ~, it does not matter the element immediately behind matches.

    document.querySelector("a ~ p") // => <p>Hello i am another paragraph</p>
    

    Enter fullscreen mode

    Exit fullscreen mode

    and we can see that the pre element did not affect the result because it does not matter if the pre was there in the first place. But the following selector will fail because it checks the element immediately above it.

    document.querySelector("a + p") // => null
    

    Enter fullscreen mode

    Exit fullscreen mode

    Getting elements by attribute

    An attribute selector starts with [ and ends with ] and is used as such

    <html>
        <body>
            <p style="color:blue;">Hello i am styled</p>
            <p>Hello i have no style</p>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector("p[style]") // => <p style="color:blue;">Hello i am styled</p>
    

    Enter fullscreen mode

    Exit fullscreen mode

    Check attribute value

    To check an attribute value we use the = symbol.

    <html>
        <body>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector('a[href="https://awesomeplace.com"]') // => <a href="https://awesomeplace.com">Hey I am a link</a>
    

    Enter fullscreen mode

    Exit fullscreen mode

    More with attribute values

    • Check if attribute starts with…
    document.querySelector('a[href^="https://awesome"]') // => <a href="https://awesomeplace.com">Hey I am a link</a>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • Check if attribute ends with…
    document.querySelectorAll('a[href$=".com"]') // => NodeList[a,a]
    

    Enter fullscreen mode

    Exit fullscreen mode

    • Check if the attribute contains a substring
    document.querySelectorAll('a[href*="place"]') // => NodeList[a,a]
    

    Enter fullscreen mode

    Exit fullscreen mode

    Advanced selectors

    • :focus

    This selects the element that currently has focus

    • :visited

    This is used with a tags and selects links that have been visited

    • :link

    This is also used with a tags but in this case, selects links that have not been visited

    • :enabled

    This selects elements that are enabled(not disabled)

    <html>
        <body>
            <p>I am a paragraph</p>
            <p>I am another paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
            <button disabled="true"> I have been disabled </button>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelectorAll(":enabled") // => NodeList[p,p,a,a]
    

    Enter fullscreen mode

    Exit fullscreen mode

    • :disabled

    This selects elements that have been disabled

    <html>
        <body>
            <p>I am a paragraph</p>
            <p>I am another paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
            <button disabled="true"> I have been disabled </button>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector(":disabled") // => <button disabled="true"> I have been disabled </button>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • :first-child

    This selects the element that is the first child of its parent

    <html>
        <body>
            <p>I am a paragraph</p>
            <p>I am another paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector("p:first-child") // => <p>I am a paragraph</p>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • :last-child

    This selects the element that is the last child of its parent

    <html>
        <body>
            <p>I am a paragraph</p>
            <p>I am another paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector("p:last-child") // => <a href="anotherplace.com">I am another link</a>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • el:first-of-type

    This selects the element that is the first child of its parent and is the same type as el

    <html>
        <body>
            <p>I am a paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <p>I am another paragraph</p>
            <a href="https://anotherplace.com">I am another link</a>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector("a:first-of-type") // => <a href="https://awesomeplace.com">Hey I am a link</a>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • el:last-of-type

    This selects the element that is the last child of its parent and is the same type as el

    <html>
        <body>
            <p>I am a paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <p>I am another paragraph</p>
            <a href="https://anotherplace.com">I am another link</a>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector("p:last-of-type") // => <p>I am another paragraph</p>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • :not(selector)

    This selects elements that don’t match the selector

    <html>
        <body>
            <p>I am a paragraph</p>
            <a href="https://awesomeplace.com">Hey I am a link</a>
            <a href="https://anotherplace.com">I am another link</a>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector(":not(a)") // => <p>I am a paragraph</p>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • :nth-child(n)

    This selects the element that is the n th child of its parent.

    <html>
        <body>
            <div>
                <p>I am a paragraph</p>
                <a href="https://awesomeplace.com">Hey I am a link</a>
                <a href="https://anotherplace.com">I am another link</a>
            </div>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector("div:nth-child(2)") // => <a href="https://awesomeplace.com">Hey I am a link</a>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • :nth-last-child(n)

    This selects the element that is the n th to the last child of its parent.

    <html>
        <body>
            <div>
                <p>I am a paragraph</p>
                <a href="https://awesomeplace.com">Hey I am a link</a>
                <a href="https://anotherplace.com">I am another link</a>
            </div>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector("div:nth-last-child(1)") // => <a href="https://anotherplace.com">I am another link</a>
    

    Enter fullscreen mode

    Exit fullscreen mode

    Mix and match

    These selectors can be mixed together to perform some complex checks. e.g

    • A disabled button of class ‘btn’
    <html>
        <body>
            <div>
                <p>I am a paragraph</p>
                <a href="https://awesomeplace.com">Hey I am a link</a>
                <a href="https://anotherplace.com">I am another link</a>
            </div>
            <button disabled="true">I am disabled</button>
            <button disabled="true" class="btn">I am also disabled</button>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector('button.btn:disabled') // => <button disabled="true" class="btn">I am also disabled</button>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • All disabled buttons in a form
    <html>
        <body>
            <form method="POST">
                <input type="text" name="firstname" placeholder="firstname"/>
                <input type="text" name="lastname" placeholder="lastname"/>
                <button disabled="true">Clear inputs</button>
                <button type="submit">Submit</button>
            </form>
            <button disabled="true">I am disabled</button>
            <button disabled="true" class="btn">I am also disabled</button>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelector('form > button:disabled') // => <button disabled="true">Clear inputs</button>
    

    Enter fullscreen mode

    Exit fullscreen mode

    • All disabled buttons in a form and all buttons outside it
    <html>
        <body>
            <form method="POST">
                <input type="text" name="firstname" placeholder="firstname"/>
                <input type="text" name="lastname" placeholder="lastname"/>
                <button disabled="true">Clear inputs</button>
                <button type="submit">Submit</button>
            </form>
            <button>I am not disabled</button>
            <button class="btn">I am also not disabled</button>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelectorAll('form > button:disabled, form ~ button') // => NodeList[button, button, button]
    

    Enter fullscreen mode

    Exit fullscreen mode

    • All links to external pages
    <html>
        <body>
            <div>
                <p>I am a paragraph</p>
                <a href="https://awesomeplace.com">Hey I am a link</a>
                <a href="https://anotherplace.com">I am another link</a>
            </div>
            <a href="/otherpage.html">I will to the other pages</a>
        </body>
    </html>
    

    Enter fullscreen mode

    Exit fullscreen mode

    document.querySelectorAll('a[href^="https://"]') // => NodeList[a,a]
    

    Enter fullscreen mode

    Exit fullscreen mode

    And to get links that are not to external pages, use

    document.querySelector('a:not([href^="https://"])') // => <a href="/otherpage.html">I will to the other pages</a>
    

    Enter fullscreen mode

    Exit fullscreen mode

    Conclusion

    These are just some of the ways you can use selectors in javascript and if you want to know more, here is a link to a CSS selector reference on w3c.

    Thanks for reading!!!

    Добавить комментарий