JavaScript, create anchor with array, doesn't work [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 1 year ago.
I tried using jsfiddle, it works properly there, but for whatever reason, the file didn't work when i run it on chrome. i also have other code concurrently (specifically form validation) but they are working fine, and there are no clashing var and function too. I know that i should just use other simpler way but unfortunate this is part of the requirement to use array in the dropdown
function makeAnchor() {
var div = document.createElement('div');
var options = ['ENCLOSED SPACE SANITISATION', 'EVENT HYGIENE MANAGEMENT', 'WIDE AREA SANITISATION', 'OBJECT DISINFECTION'];
for (var i = 0; i < options.length; i++) {
// Create the list item:
var a = document.createElement('a');
var ok = options[i]
a.href = "./service" + (i + 1) + ".html"
a.appendChild(document.createTextNode(ok));
div.appendChild(a);
}
return div;
}
document.getElementById('dropsc').appendChild(makeAnchor());
<!-- Nav Bar -->
<nav class="sticky-top">
<ul>
<li class="dropdown font-josefin">
<a class="dropbtn">SERVICES</a>
<div id="dropsc" class="dropdown-content">
<!-- ENCLOSED SPACE SANITISATION
EVENT HYGIENE MANAGEMENT
WIDE AREA SANITISATION
OBJECT DISINFECTION -->
</div>
</li>
<li class="font-josefin">ABOUT ME</li>
<li class="font-josefin">ENQUIRY</li>
<li class="font-josefin">ENHANCEMENTS</li>
<li class="font-josefin">DISCLAIMER</li>
</ul>
</nav>

document.getElementById('dropsc').appendChild(makeAnchor().cloneNode(true));
Try this

Related

Get href list under HTML content

I have a json string which contains HTML element. What I am trying to achieve is to fetch all anchor tag value <a> in that string.
Json String
"content" : "<p>Reference information</p> <ul> <li>My Url</li> <li>Your Url</li> </ul>"
Here is HTML Format
<p>Reference information</p>
<ul>
<li>My Url</li>
<li>Your Url</li>
</ul>
I have tried like this but cannot get exact value:
<div id="TestDiv" hidden >
</div>
let anchor = document.getElementById("TestDiv").getElementsByTagName("li");
anchor[0].innerHTML
I am getting this value
My Url
But I want to get https://myurl.com
another way I tried which was closed though still has problem but don't want to use regex:
content.match(/href="([^"]*?)"/);
How can I achieve that?
// Create an element
const el = document.createElement("div");
// set the inner HTML
el.innerHTML = `
<p>Reference information</p>
<ul>
<li>My Url</li>
<li>Your Url</li>
</ul>
`;
// grab all <a> tag
const nodeList = el.querySelectorAll("a");
// convert to array
const nodeArray = [...nodeList];
// map to href
const hrefs = nodeArray.map((a) => a.href); // ["https://myurl.com/", "https://yoururl.com/"]
You can use Array.prototype.map like:
var anchorUrls = Array.prototype.map.call(
document.anchors, (i) => i.href;
);
console.log(anchorUrls);
You can access the href attribute value using .href or using the getAttribute("href") method. However you are currently getting the li elements, but you want to instead get the anchor elements.
let anchor = document.getElementById("TestDiv").getElementsByTagName("a");
anchor[0].href;
To get all of the href's you will need to loop through the array of anchors.
var i;
for (i = 0; i < anchor.length; i++) {
anchor[i].href;
}

How to pass variables when adding 'onclick' with JS

I'm having a problem with a simple tabbed page.
It all works OK if I hard code the 'onclicks' in the tabs that appear at the top of the page like this:
<ul class="tabs" data-persist="true">
<li class='tablinks' onclick="openTab('view1')" id='default'>How to find Maolbhuidhe</li>
<li class='tablinks' onclick="openTab('view2')">How to get to Mull</li>
<li class='tablinks' onclick="openTab('view3')">Map of Mull</li>
<li class='tablinks' onclick="openTab('view4')">Map of Scotland</li>
</ul>
There's a JS file containing the function 'openTab', of course.
But when I try to add the onclick events via JS/jQuery after the page has loaded, I'm running into a problem. The HTML for this section now looks like this:
<ul id='toptabs' class="tabs" data-persist="true">
<li class='tablinks' id='default'>How to find Maolbhuidhe</li>
<li class='tablinks'>How to get to Mull</li>
<li class='tablinks'>Map of Mull</li>
<li class='tablinks'>Map of Scotland</li>
</ul>
The JS script I'm using to add the onclick events is:
function applyClicks() {
var toptabs = document.getElementById("toptabs");
var lnks = toptabs.getElementsByTagName("li");
for (var i=0; i<lnks.length; i++) {
var k = (i+1)
var vw = 'view' + k;
alert ('vw is: ' + vw);
lnks[i].onclick = (function() {
openTab('view' + k);
});
}
}
The problem seems to lie in providing the parameter to 'openTab()'. I've tried several variations, the one shown ends up as "openTab('view' + k)" (As seen in Inspector DOM). If I hard code it as 'view1' it works, but of course all the links are then the same, so only the first tab can be shown. It seems whatever I put in the JS function as the parameter gets treated as a literal.
What do I need to do to make the parameter 'view1', 'view2', 'view3', 'view4' (as in the hard coded version) according to the value of i ? This was the purpose of the var 'vw', which duly shows all the right values in turn as the script runs, but just shows up in the link on the page as 'vw'
I've also tried the widely recommended 'addEventListener('click', ...) etc. but I get the same problem (or something similar). It may be better to add an event listener eventually, but first I need to resolve the problem of passing the variable to the 'Click'.
Try it like this:
$('.tablinks').click(function(){
let idx = $(this).index() + 1;
//alert('view' + idx);
openTab('view' + idx);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<ul id='toptabs' class="tabs" data-persist="true">
<li class='tablinks' id='default'>How to find Maolbhuidhe</li>
<li class='tablinks'>How to get to Mull</li>
<li class='tablinks'>Map of Mull</li>
<li class='tablinks'>Map of Scotland</li>
</ul>
This is why many of us prefer writing jQuery - it's just simpler. And shorter.
An alternative way of doing it is using data attributes...
$('.tablinks').on("click", function() {
var openValue = $(this).data("open");
//openTab(openValue);
console.log(openValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<ul id='toptabs' class="tabs" data-persist="true">
<li class='tablinks' data-open="view1" id='default'>How to find Maolbhuidhe</li>
<li class='tablinks' data-open="view2">How to get to Mull</li>
<li class='tablinks' data-open="view3">Map of Mull</li>
<li class='tablinks' data-open="view4">Map of Scotland</li>
</ul>

List items from HTML XPath

I need to list items returned from evaluating an Xpath. I'd like to return the tweets in a list, so I can further evaluate their elements. How do I do this?
My code is:
var navigable_stream = '//*[#id="stream-items-id"]';
var FIRST_RECORD = document.evaluate(navigable_stream, document, null, XPathResult.ANY_TYPE, null).iterateNext();
console.log(FIRST_RECORD);
And the returned HTML is very long. But it has lots of tweets with different ids. Here's a picture to show what I mean:
Update
" Is there a way to match the first part of the element id i.e. 'stream-item-tweet"?"
Yes, by using referencing the partial #id as an attribute:
var tweet = document.querySelectorAll("[id^=stream-item-tweet]");
Note the ^= means that the beginning of the #id must match stream-item-tweet
Having answered the question I'd like to add that there may be a better alternative by using the class of each <li>:
var tweet = document.querySelectorAll('.js-stream-item')
Something looks invalid on the classList:
class="js-stream-item stream-item stream-item"
.stream-item is repeated twice...maybe it's best to avoid class in your circumstance.
Anyways, knowing the first way should work and maybe the second way might, tweet is now a NodeList which needs to be handled by a loop or it needs to be converted to an array so it can be processed by an array method.
Demo 2 shows how the latter is done.
Just guessing, since there's no way I can test it myself, that if that's what you can get on the console, then you could maybe use .toString() then parse and append it to the DOM.
Demo 1
Not possible to make an actual functioning Demo
var navigable_stream = '//*[#id="stream-items-id"]';
var FIRST_RECORD = document.evaluate(navigable_stream, document, null, XPathResult.ANY_TYPE, null).iterateNext();
console.log(FIRST_RECORD);
var str = FIRST_RECORD.toString();
document.getElementById('dock01').insertAdjacentHTML('beforeend', str);
<section id='dock01'></section>
Demo 2
/* Collect all elements with an #id that starts with "tweet"
|| Convert NodeList into an array
*/
var tweets = Array.from(document.querySelectorAll("[id^=tweet]"));
/* filter() the array tweets
|| if an item has data-id = "retweet"
|| add it to the new array retweets
*/
var retweets = tweets.filter(function(t) {
return t.dataset.id === "retweet";
});
console.log(retweets);
/* The lazy way to add text */
li::after {
content: attr(id);
}
/* This is just so the console results don't obscure the Demo*/
.as-console-wrapper {
width: 70%;
margin-left: 30%;
}
.as-console-row:after {
display: none !important;
}
<ol>
<li id='tweet-51515151' data-id='retweet'></li>
<li id='tweet-57885157' data-id='tweet'></li>
<li id='tweet-51677459' data-id='tweet'></li>
<li id='tweet-51890331' data-id='retweet'></li>
<li id='tweet-51515337' data-id='retweet'></li>
<li id='tweet-51593051' data-id='retweet'></li>
<li id='tweet-51333333' data-id='tweet'></li>
<li id='tweet-51534152' data-id='tweet'></li>
<li id='tweet-51599951' data-id='tweet'></li>
<li id='tweet-54785151' data-id='retweet'></li>
<li id='tweet-56785199' data-id='retweet'></li>
<li id='tweet-51557844' data-id='tweet'></li>
<li id='tweet-51510000' data-id='retweet'></li>
</ol>

How to get the id's within the html tags [duplicate]

This question already has answers here:
How to get an array of attribute value from elements in a jQuery object
(3 answers)
Closed 7 years ago.
I'm trying to do a screen scraping on twitter, i'm using Jsoup library and this is a sample of html code of the page :
<div class="stream permalink-stream">
<ol id="stream-items-id" class="stream-items js-navigable-stream">
<li id="stream-item-tweet-692459333712347137" class="js-stream-item stream-item stream-item expanding-stream-item " data-item-type="tweet" data-item-id="692459333712347137">
<li id="stream-item-tweet-692470683348123649" class="js-stream-item stream-item stream-item expanding-stream-item " data-item-type="tweet" data-item-id="692470683348123649">
<li id="stream-item-tweet-692489785978523648" class="js-stream-item stream-item stream-item expanding-stream-item " data-item-type="tweet" data-item-id="692489785978523648">
</ol>
<ol class="hidden-replies-container"></ol>
</div>
what I'm trying to do first is to get all id's of the li tags in the web page, to use them after in a loop to get the text inside each li tag.
the result I want, is something like :
id1 = stream-item-tweet-692459333712347137
id2 = stream-item-tweet-692489785978523648
id3 = stream-item-tweet-692489785978523648
I've tried something like with Jsoup, but it doesn't work :
Elements scriptElements = doc.getElementsByTag("li");
for (Element element :scriptElements ){
for (DataNode node : element.dataNodes()) {
System.out.println(node.getWholeData());
}
}
thanks !
here's an example:
$('ol').find('li').each(function(k,v)
{
alert('id = ' + $(this).attr('id'));
});

History.pushState URL + Scroll To Effect

I'm changing my sites URLs to /name using History.pushState, which is working but the page does not scroll to the location of the site it is suppose to.
index.php:
<nav>
<ul>
<li>Work</li>
<li>About</li>
<li>Services</li>
<li>Blog <!-- Coming Soon... --> </li>
<li>Contact</li>
</ul>
</nav>
<article class="content" id="work">
...
<article class="content" id="about">
...
jquery.page.js:
_saveState = function( chapter ) {
if (History.getState().url.queryStringToJSON().chapter !== chapter) {
var page;
if (chapter == 1)
page = "/work";
if (chapter == 2)
page = "/about";
if (chapter == 3)
page = "/services";
if (chapter == 4)
page = "/blog";
if (chapter == 5)
page = "/contact";
else
page = '?chapter=' + chapter;
History.pushState(null, null, page)
}
},
...
_goto = function( chapter ) {
var chapter = chapter || History.getState().url.queryStringToJSON().chapter,
isHome = ( chapter === undefined ),
$article = $( chapter ? '#' + 'chapter' + chapter : '#' + 'introduction' );
...
When the user clicks on a link in the navigation menu, how do I make the page jump to the location it is suppose to, as seen in the tutorial I've been following?
their is no problem in your javascript its prefect but the problem was in your html please correct the content-wrapper div it was not enclosing the articles it was like
<div class="content-wrapper"></div><article></article>...
it should be
<div class="content-wrapper"><article></article>....</div>
History.getState().url.queryStringToJSON().chapter is trying to find a query parameter chapter in your URL, which doesn’t exist anymore since you changed the URL format.
Without having worked with $.History, it seems to me that you could try to compare against the URL, using something along the lines of:
if (History.getState().hash.replace(/^\/|\/$/g, '') !== chapter) { ... }
// replace(/^\/|\/$/g, '') will remove a leading and/or trailing slash '/'
Note though, that if your site does not live on the root (e.g. http://example.com/foo/bar/portfolio) you’ll still have to deal with the rest of the URL, since History.getState().hash will return you /foo/bar/portfolio instead of /portfolio.
(On a side note: If you find yourself writing repeatedly else if, try using a switch instead.)

Categories