getElementById using substring of the id: Angular 4 - javascript

I'm using ADAL for authenticating user for using my Angular 4 application. By when I use the following method from Adal.js:
acquireToken // https://msdn.microsoft.com/en-gb/library/microsoft.identitymodel.clients.activedirectory.authenticationcontext.acquiretoken.aspx
it creates an iFrame that I would like to delete once the token is acquired. But, the id of that iFrame is dynamic, it starts with something like: "adalRenewFrame...." and then the token (which is just a string of characters). So is there a way to get that element by using substring "adalRenewFrame"?

Assuming that you can get id of iFrame. You can use startsWith() function of Javascript. Below is working example:
var id = "adalRenewFrame23219874033";
var fixWord = "adalRenewFrame";
if (id.startsWith(fixWord)) {
console.log("true"); // will return true
// you code to remove iFrame here
} else {
console.log("false")
}

Yes. It is simple. Use document.querySelector API with a CSS attribute based selector.
function deleteIFrame() {
// It selects iframe whose id contains adalRenewFrame
const iFrame = document.querySelector(`iframe[id*='adalRenewFrame']`)
if (iFrame) {
iFrame.parent.removeChild(iFrame);
}
}
Of you can also use attribute starting with selector like document.querySelector("iframe[id^='adalRenewFrame']").
Additionally, if you know some parent element by its ID or CLASS, you can use it to scope your query search.
Refer to MDN docs for more available selectors.

Related

How to find a specific link from an href using JavaScript?

This is my first experience with JS, so please forgive the noob question.
I'm trying to make a userscript for a phpBB forum that'll allow me to automatically bookmark every topic I create.
My approach is to add an onclick listener to the submit button.
I'll use the code found in another question:
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
;
}
Before that though I want to find a link to bookmarking the topic in one of the hrefs on the page and store it as a variable.
I know that it will always take the form of
<a href="./viewtopic.php?f=FORUM_NUMBER&t=TOPIC_NUMBER&bookmark=1&hash=HASH"
The final code should look something like (hopefully it's the correct form)
var link = THE LINK EXTRACTED FROM THE MATCHED HREF
var submit = document.getElementsByTagName('input')[0];
submit.onclick = function() {
setTimeout(function(){ window.location.href = 'link'; }, 1000);
}
My issue is I don't know how to approach locating the href that I need and getting the link from it. Haven't found any similar questions about this.
Thanks in advance for any help
Maybe something like this?
var anchors = document.getElementsByTagName('a'); // get all <a> tags
var link = '';
if (anchors) {
// getAttribute(attributeName) gets the value of attributeName (in your case, the value of 'href' attribute
// .map(), .find() and .filter() are available methods for arrays in JS
// .startsWith() is an available method for matching strings in JS.
// You can even experiment with other regex-based string matching methods like .match()
// Use one of the following lines, based on what you require:
// to get the first matching href value
link = anchors.map(anchor => anchor.getAttribute('href')).find(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
// to get all matching href values as an array
link = anchors.map(anchor => anchor.getAttribute('href')).filter(url => url.startsWith('./viewtopic.php')); // or provide a better regex pattern using .match()
}
Since you're not new to coding, check out this documentation if you're new to JS :)
Happy coding!
You can try document.getElementsByTagName("a"); which returns a collection of all the <a></a> loaded in the dom.
Then you can find it in the list and and use .href to get it's href attribute.

Traversing elements in javaScript

I need to change the href of link in a box. I can only use native javaScript. Somehow I have problems traversing through the elements in order to match the correct <a> tag.
Since all the a tags inside this container are identical except for their href value, I need to use this value to get a match.
So far I have tried with this:
var box = document.getElementsByClassName('ic-Login-confirmation__content');
var terms = box.querySelectorAll('a');
if (typeof(box) != 'undefined' && box != null) {
for (var i = 0; i < terms.length; i++) {
if (terms[i].href.toLowerCase() == 'http://www.myweb.net/2/') {
terms[i].setAttribute('href', 'http://newlink.com');
}
}
}
However, I keep getting "Uncaught TypeError: box.querySelectorAll is not a function". What do I need to do in order to make this work?
Jsfiddle here.
The beauty of querySelectorAll is you dont need to traverse like that - just use
var terms = document.querySelectorAll('.ic-Login-confirmation__content a');
And then iterate those. Updated fiddle: https://jsfiddle.net/4y6k8g4g/2/
In fact, this whole thing can be much simpler
var terms = document.querySelectorAll('.ic-Login-confirmation__content a[href="http://www.myweb.net/2/"]');
if(terms.length){
terms[0].setAttribute('href', 'http://newlink.com');
}
Live example: https://jsfiddle.net/4y6k8g4g/4/
Try This:
var box = document.getElementsByClassName('ic-Login-confirmation__content')[0];
Since you are using getElementsByClassName ,it will return an array of elements.
The getElementsByClassName method returns returns a collection of all elements in the document with the specified class name, as a NodeList object.
You need to specify it as follows for this instance:
document.getElementsByClassName('ic-Login-confirmation__content')[0]
This will ensure that you are accessing the correct node in your HTML. If you console.log the box variable in your example you will see an array returned.
you can select by href attr with querySelector,
try this:
document.querySelector('a[href="http://www.myweb.net/2/"]')
instead of defining the exact href attribute you can simplify it even more :
document.querySelector('a[href?="myweb.net/2/"]'
matches only elments with href attribute that end with "myweb.net/2/"

How to retrieve particular ID elements within a web page using jQuery?

I am unsure how to approach this for the web page that I am on (i.e. in my web app) using jQuery. I would like to be able to add to an array in order of appearance through the web page, all elements where the id matches the string "_AB_Q_"
For example, scattered through the web page will be instances of the following:
<id="P1_AB_Q_101">...
<id="P1_AB_Q_102">...
<id="P1_AB_Q_103">...
<id="P1_AB_Q_104">...
..
...
....
<id="P1_AB_Q_500">...
As mentioned, I only want to retrieve full id names where the id matches the pattern "_AB_Q_" and then store these in an array for later processing.
So using the test data above, I want to only return:
P1_AB_Q_101
P1_AB_Q_102
P1_AB_Q_103
P1_AB_Q_104
P1_AB_Q_500
You need to use the attribute contains selector:
Ive created a Jsfiddle for you: http://jsfiddle.net/whizkid747/D2HS4/
$('[id*="_AB_Q_"]').each(function(){
alert(this.getAttribute('id'));
});
documentation: http://api.jquery.com/attribute-contains-selector/
$('[id^="_AB_Q_"]').each(function(){
console.log(this.getAttribute('id'));
});
Use the attribute contains selector and the map function;
var ids = $('[id*="_AB_Q_"]').map(function() { return this.id });
Not tested but it should work :)
My approch would be:
var ids = []
$("*").each(function(){
if(this.id.match(/_AB_Q_/))
ids.push(this.id)
});
is more or less the same as the other onces, but i seperated the match condtion, to make it easy to adapt. :)
$('[id^=_AB_Q_]').doSomeAction();
It checks if an id starts with the string provided.
JQuery selectors are css selectors. For a complete list you should check http://www.w3.org/TR/CSS2/selector.htm
edit:
// if the id = AB_Q_P1_100
// you can retrieve different parts of the id like this
var parts = $(this).attr('id').split('_');
var p = parts['3'];

Javascript Regex and getElementByID

I'm trying to search for all elements in a web page with a certain regex pattern.
I'm failing to understand how to utilize Javascript's regex object for this task. My plan was to collect all elements with a jQuery selector
$('div[id*="Prefix_"]');
Then further match the element ID in the collection with this
var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
//Then somehow match it.
//If successful, modify the element in some way, then move onto next element.
An example ID would be "Prefix_25412_Suffix". Only the 5 digit number changes.
This looks terrible and probably doesn't work:
1) I'm not sure if I can store all of what jQuery's returned into a collection and then iterate through it. Is this possible?? If I could I could proceed with step two. But then...
2) What function would I be using for step 2? The regex examples all use String.match method. I don't believe something like element.id.match(); is valid?
Is there an elegant way to run through the elements identified with a specific regex and work with them?
Something in the vein of C#
foreach (element e in
ElementsCollectedFromIDRegexMatch) { //do stuff }
Just use the "filter" function:
$('div[id*=Prefix_]').filter(function() {
return /^Prefix_\d+_Suffix$/.test(this.id);
}).each(function() {
// whatever you need to do here
// "this" will refer to each element to be processed
});
Using what jQuery returns as a collection and iterating through it is, in fact, the fundamental point of the whole library, so yes you can do that.
edit — a comment makes me realize that the initial selector with the "id" test is probably not useful; you could just operate on all the <div> elements on the page to start with, and let your own filtering pluck out the ones you really want.
You can use filter function. i.e:
$('div[id*="Prefix_"]').filter(function(){
return this.id.match(/Prefix_\d+_Suffix/);
});
You could do something like
$('div[id*="Prefix_"]').each(function(){
if($(this).attr('id').search(/do your regex here/) != -1) {
//change the dom element here
}
});
You could try using the filter method, to do something like this...
var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
$('div[id*="Prefix_"]').filter(function(index)
{
return $(this).attr("id").search(pattern) != -1;
}
);
... and return a jQuery collection that contains all (if any) of the elements which match your spec.
Can't be sure of the exact syntax, off the top of my head, but this should at least point you in the right direction

Locating text and performing operation based on its existence

I'm trying to learn jQuery, but it's coming slowly as I really don't know any JavaScript.
My site is in VB.NET and I'm putting jQuery code on both my actual .ascx UserControl and in a separate file (something like myscripts.js). This is because I'm using webforms as I still don't know MVC well enough to implement it, so I have to get the clientID's on the page.
What I would like to do is the following:
Grab text from a textbox and make it all lowercase
Get the username from the login info. I've done this like so on my actual page:
var userName = "<%=Split(System.Web.HttpContext.Current.User.Identity.Name.ToLowerInvariant, '|')%>";
Check to see if the username is in the text. If it IS in the text, I want to set a variable to "false", othewise to true.
How do I do this?
I am completely ignorant of the ASP.NET side of it, but as far as jQuery and Javascript....
To get the value of a text field, you use the jQuery function val():
var value = $('#mytextbox').val();
To turn a string to lower case, you use the string method toLowerCase():
var value = $('#mytextbox').val().toLowerCase();
Since val() returns a string we can throw that at the end.
To check if a string is within another string, you use the string method indexOf():
var needle = 'Hello';
var haystack = 'Hello World';
var match = haystack.indexOf(needle); // -1 if no matches, 0 in this case
Another thing to remember is that ASP.NET renames all your control ID's. To access your controls in JavaScript, you should use the following in place of the Control ID <%= txtUserName.ClientID %>.
In jQuery, here is what my selector would look like for a textbox with the ID "txtUserName".
$('#<%= txtUserName.ClientID %>')
Enjoy,
Zach
var userName = "username as it comes out of your web app";
// stuff happens
var $myTextbox = $('#ID_of_textbox');
var userNameIsContained = $myTextbox.val().toLowerCase().indexOf(userName) >= 0;
Short explanation:
$('#ID_of_textbox') // fetches the jQuery object corresponding to your textbox
.val() // the jQuery function that gets the textbox value
.toLowerCase() // self explanatory
.indexOf() // returns the position of a string in a string (or -1)
See the JavaScript String object reference at w3schools.
Alternative (to check if the textbox value equals the username):
var userNameIsEqual = $myTextbox.val().toLowerCase() == userName;
The basics of JQuery are like so: Find a list of dom elements, and perform actions on them.
In your case, you should start off by finding the dom element that is your testbox. For example's sake, we'll choose $('#userName'). The selector # means "id" and together with the name "userName" it finds all elements with the id of "userName". (Ids on a page should be unique if you're following best practices.)
Once you have that list (in this case, a list of one element), you can ask it what the value is.
$('#userName').val()
This gets you the value of the value="" attribute of the input tag.
You can then assign it to a variable and use standard javascript String functions to do the rest!
function checkLogin(userName){
return $('#mytextbox').val().toLowerCase() == userName
}
if ($("#textBoxID").val()) != "") { /*Do stuff*/ }

Categories