This is the code I'm using to try and get all the hrefs ONLY from the nav:
componentDidMount(){
$("nav ul li a").each(function(k, j){
console.log(j);
});
}
From this I am successfully getting all of the dom elements printed out on the console as such:
<a href="#home" class="nav-link">Home</a>
<a href="#about" class="nav-link">About</a>
...etc...
Now to try and actually pull out the href string, I've attempted many things such as trying to console.log(j.attr('href'))
(in the loop shown above), but have nothing working yet. (TypeError: j.attr is not a function)
What should I use for this? and also my application is built in ReactJS so I was wondering if there was maybe a more appropriate way to achieve this, with something such as refs
Many thanks
if you want to get rid of slicing the string which u get using j.href, you can even use getAttribute on j.
$("a").each(function(k, j) { console.log(j.getAttribute("href")); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#home" class="nav-link">Home</a> <a href="#about" class="nav-link">About</a>
Here's a working solution. Hope it helps!
$("a").each(function(){ console.log($(this).attr("href")); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <a href="#home" class="nav-link">Home</a> <a href="#about" class="nav-link">About</a>
one line change in your code
$("nav ul li a").each(function(k, j){ console.log($(this).attr('href')); });
<script src="https://code.jquery.com/jquery-1.10.2.js"></script> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">WebSiteName</a> </div> <ul class="nav navbar-nav"> <li class="active"><a href="home">Home</a></li> <li><a href="page1">Page 1</a></li> <li><a href="page2">Page 2</a></li> <li><a href="page3">Page 3</a></li> </ul> </div> </nav>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.