I'm trying to use JavaScript to create an ID for my links and also to tell it where to link to.
My JavaScript has generated a link element in my HTML:
<a id = "NB4-CAXL-14U-12-AAG"> Link Text </a>
And that appears as it should.
I then have a variable eopartnum[i]:
console.log(eopartnum[i]); //output: NB4-CAXL-14U-12-AAG
This variable matches my ID for my link above. Then i tried to access that link via the ID and assign an href to it, like so:
var linktoprod = document.getElementById(eopartnum[i]);
console.log(linktoprod); //returns null
linktoprod.href = "http://www.enviroptics.com/"; //Cannot set property 'href' of null(…)
Why does my linktoprod come up as null? Is my syntax wrong?
JSfiddle for full code: http://jsfiddle.net/98oL12tk/17/ Lines 106-109 in JS section.
The problem is that you are calling getElementById() before you append the table to the document. At the time that you are querying for the ID, it doesn't yet exist. This example seems a bit contrived; I think you could just set firstcelllink.href = 'http://www.enviroptics.com/';
EDIT: probably more appropriate to use firstcelllink.setAttribute('href', 'http://www.enviroptics.com/');
Related
I am trying to get the patientNumber (ClinicA100-PF-TR1-P1) using querySelector. I keep getting a NULL value. The patientNumber is at the top of the page and the script is at the bottom. Even after the page is loaded, I click a button that runs the function and it still returns a NULL value.
Here is a screenshot of the selectors (https://recordit.co/IypXuuXib0)
<script type="text/javascript">
function getPatientNumber(){
var patientNumber = document.querySelector("patientNumber");
console.log(patientNumber);
console.log("hello");
return patientNumber;
}
var patientNumber = getPatientNumber();
console.log(patientNumber);
_kmq.push(['identify', patientNumber]);
</script>
Thank you for any help you can provide.
ADDITIONAL HTML INFORMATION:
I am using Caspio (database management software) to create this HTML code. I don't know if that may be the cause of the issue. Here is the HTML CODE.
<p class="sponsorName" id="sponsorNameID">[#authfield:User_List_Sponsor_Name]</p>
<p class="clinicNumber" id="clinicNumberID">[#authfield:User_List_Site_Number]</p>
<p class="protocolNumber" id="protocolNumberID">[#authfield:User_List_Protocol_Number]</p>
<p class="patientNumber" id="patientNumberID">[#authfield:User_List_Patient_Number]</p>
You are missing a dot.
var patientNumberNode = document.querySelector(".patientNumber");
var patientNumber = patientNumberNode.innerText;
if you select the item with class".", if you select with id, you should use"#".
var patientNumber = document.querySelector(".patientNumber"); // class select
var patientNumber = document.querySelector("#patientNumber"); // id select
Your selector is incorrect. It should be
var patientNumber = document.querySelector(".patientNumber");
Why is it failing:
When you use patientNumber as the selector, JavaScript looks for an element with a name of patientNumber. Since that's not the case, and you are looking for an element with a class of patientNumber, you need to use the . notation.
Addon Suggestion (can be ignored):
Since you are also using IDs, consider using document.getElementById() as it is faster than using document.querySelector().
Note that if you use document.getElementById(), your .patientNumber selector won't work. You need to write it as
document.getElementById('patientNumberID');
//ID based on the screenshot of the DOM you've shared
While the code is at the bottom of the page, and the element is at the top, it is not loaded asynchronously as it comes from a third party database. i put a delay in the getPatientNumber() and it works now.
I can't manage to make jQuery add the content of #quote (which is a paragraph with a string generated via foresmatic API).The full code is here: https://codepen.io/raffaele2692/pen/GvrvxM .... Can you help me? :)
<a type="button" class="twitter-share-button"
href="https://twitter.com/intent/tweet"
data-size="small"
data-text="">
Tweet</a>
<script>
var textQuote = document.getElementByID("#quote");
$("a").attr("data-text", textQuote);
</script>
You have some issues in the js code. You do not need to add "#" to the id for getElementByID call , also to get the text of a HTML element you can use text method.
<script>
var textQuote = $("#quote").text();
$("a").attr("data-text", textQuote);
</script>
I think textQuote is a HtmlElement object, not the value you want to assign.
you should get the value in quote first.
btw, jquery has a method called data to assign value to data attributes.
I "learned" JavaScript a few months ago but quickly picked up Python and spent the past few months writing programs in that language, so I decided it would be a good idea to go back and actually learn JavaScript. Right now I'm making a very simple "blog" with JS that takes the title of the post, generates a hash link from the post, and creates a recent posts section where you can click the link to jump to the post in the page.
For instance, say one of the posts is formatted like this:
<h2 class="post">Another post for you</h2>
<h4>I know you love these</h4>
With multiple posts, and an empty container at the bottom, which will be used to append the recent posts links:
<div id="get-post"></div>
My JS code basically grabs each title with the post class and creates a hash link from the element's title (removing spaces and commas). It then creates and appends a text node consisting of the post title, and then appends the entire link into the get-post container.
var postList = $('#get-post');
var post = $('.post');
function generateRecentPosts() {
post.each(function() {
// Create link from post title that will be used to
// access that post.
var postLink = document.createElement('a');
// Create text node from post title that will be appended
// to the postLink.
var text = document.createTextNode($(this).html());
// Add elements to the DOM.
postLink.href = createLocalLink($(this));
postLink.appendChild(text);
postList.append(postLink);
postList.append('<br />');
});
}
function createLocalLink(elm) {
// Creates the href link that will be used to go to a blog post.
// For example, if the title of the elm parameter is "My Post",
// a link is created called #My-Post that will be used to access
// that post.
elm.id = elm.html().replace(/,/g, '').replace(/\s/g, '-');
console.log(elm.id); // Make sure the ID is added.
return '#' + elm.id;
}
generateRecentPosts();
My problem is that the links it generates to not point to the ID created for each title. When I click on the link, I can see that it successfully created the href hash #My-Post and added it to the anchor tag, but it doesn't take me to the post title.
Example: http://jsfiddle.net/samrap/GQtxL/
I even added a console log function to make sure the ID is being added to the title as I thought that was the problem, but it isn't because the console is printing the correct new ID. I could really use some help in figuring out where exactly the problem is here.
Your h2 tags need to have an id or name attribute that corresponds with the link, that is what makes internal links work. The id is not getting added because you are accessing a jQuery object as if it were a DOM node (elm.id = ...). Modify your createLocalLink function to use jQuery's attr method to set the id property:
elm.attr('id', elm.html().replace(/,/g, '').replace(/\s/g, '-'));
Additionally, since you have jQuery available you could whittle your code down to:
var $this = $(this),
link = createLocalLink($this);
var $postLink = $('a', {
text: $this.text(),
href: link
})
postList.append($postLink).append('<br />');
Here is your fiddle updated: http://jsfiddle.net/GQtxL/1/
This is because your link uses the href = "#My-Post" but none of the posts has the ID "My-Post". It only has a class "post".
This happens because the argument that your are passing to the createLocalLink() function is a DOM Node. But by doing elm.id you are not changing the DOM property but adding another property to the "elm" object. Thus your "elm" object is
x.fn.x.init[1]
0: h2.post
context: h2.post
id: "Another-post-for-you"
length: 1
__proto__: Object[0]
Thus the actual post never gets the attribute ID only "elm" object gets it. Note the empty ID attribute below
draggable: false
firstChild: text
firstElementChild: null
hidden: false
id: ""
innerHTML: "Another post for you"
innerText: "Another post for you"
Thus your document has no element with the ID "My-Post". You can view the source of your HTML to verify this.
For internal links to work there should be an element with the same ID as that used in the href attribute of the link.
For example
<div id="post1">
Your Post Here
</div>
<!--just to show the effect of moving to the post-->
<div style="clear:both; height:900px"></div>
Click Here
This would work because there is an element with the id "post1" and the link uses the href "#post1" which links it to the corresponding element. Hence, add the corresponding id to your post as well (other than your link) for it to work.
In function createLocalLink you are using elm argument as dom node, but actually passing a jQuery wrapped object to it, which don't have id property. To get it work, use elm.get(0).id = ... or elm.attr('id', elm.text().replace(/,/g, '').replace(/\s/g, '-'););
I have a span tag
<span class="vi-is1-prcp" id="v4-25">US $99.00</span>
I would like to grab it using pure javascript. JQuery or any other library is not allowed. Is that possible?
I recon that
getElementById('v4-25')
won't work since I have to specify class, too, correct?
Thank you,
So,
<div id="listprice">asdasdasdasdasd</div>
var string = document.getElementById('v4-25');
document.getElementById('listprice').innerHTML = string;
should print value of 'v4-25' in 'listpirce' ?
H
getElementById will work just fine. Just make sure you're running it after the page has loaded.
First of all, ids are unique. You can't have more than one. therefore, when you select element by id, you can only bring back one element (this is good).
Secondly, after you get an element, you have to do something with it. var string = document.getElementById('v4-25'); only gets you the element, but it looks like you want var string = document.getElementById('v4-25').innerHTML; for the price. If you do want the id instead you can do var string = document.getElementById('v4-25').id; but because that just returns "v4-25" it's a bit redundant.
There is no reason to add a class. Run the script after that dom element is loaded like this.
<span class="vi-is1-prcp" id="v4-25">US $99.00</span>
<script>
var elm = document.getElementById('v4-25');
</script>
I am trying to write a GreaseMonkey script in which I want to find all of the links that are relative links. It seemed to me that the way to do that would be to match the contents of href against /^https?:///.
But I find that when I access the anchor's href attribute, it's always normalized or cooked into a form that contains "http". That is, if the HTML contains:
<a id="rel" href="/relative/link">inner</a>
accessing
document.getElementById("rel").href
returns
http://example.com/relative/link
How can I access the raw data in the href attribute?
Alternately, is there a better way to find relative links?
Try the getAttribute method instead.
Typical. I figured it out myself almost immediately after posting the question.
instead of:
anchor.href
use:
anchor.getAttribute("href")
Of course, it took me longer to type in this answer than it took everyone else to answer it. (Damn, you people are fast.)
Here's a code snippet you could run to test.
const anchors = document.getElementsByTagName('a');
for (let anchor of anchors) {
let hrefFullPath = anchor.href;
let hrefRelativePath = anchor.attributes.href.value;
console.log('hrefFullPath', hrefFullPath);
console.log('hrefRelativePath', hrefRelativePath);
}
Let's say, you are at http://localhost:4200, and this is your document as you have shown in the question.
<a id="rel" href="/relative/link">inner</a>
This anchor's attribute value of href is:
document.getElementById('rel').attributes.href.value => /relative/link
And anchor's href value is:
document.getElementById('rel').href => http://localhost:4200/relative/link
I hope it helps.
Get the link dom and add attributes for same and append the actual link to same.
var hrefUrl = 'https://www.google.com/';
const link: HTMLLinkElement = dom?.createElement('link');
link.setAttribute('rel', 'canonical');
link.setAttribute('id', 'seo');
dom?.head?.appendChild(link);
dom?.getElementById('seo')?.setAttribute('href', hrefUrl);
// working
Hope this will work for dynamic links that to append for each dynamic pages under js / ts.