Get text value from especific class in web site - javascript

I want to know if it is possible to go to a site and retrieve the text of an element
i think something like
a = page("www.site.com")
b = a.getElementByClass("name")
console.log(b.text)
this is possible?

Yes. It's called the innerText property. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText

That depends,
If you want to get the innerText of the elements, then
let elements = document.getElementsByClassName("YourClassName");
for(let i=0;i<elements.length; i++){
/*doSOmething*/
console.log(elements[i].innerText);
}
Many elements may have same className. So, if you want to access some specific Element, then you should either know the index of the element or you need to use id for the element.
let element = document.getElementById("YourElementId");
/*doSOmething*/
console.log(element.innerText);

Related

How can I trigger a click event on a specific descendent of an element?

I am trying to click on a specific descendent of an element. I have done gotten the ancestor by ng-class because it does not have an id.
yes = document.querySelectorAll('[ng-controller = "inventoryController"]')
Now that I have the ancestor I want, I want to get the descendent. Once again, they element does not have an id, so I use ng-src to get it.
yes2 = document.querySelectorAll('[ng-src = "link.com/link/here"]')
So How would I use this code to click on the descendent? something like this?
yes[1].yes2[0].click
First, use querySelector() to get a specific element; querySelectorAll() returns a list of all the matches.
Second, use the result of the first call instead of document to only select its descendants.
yes = document.querySelector('[ng-controller = "inventoryController"]');
yes2 = yes.querySelector('[ng-src = "link.com/link/here"]');
You can also just combine the selectors.
yes2 = document.querySelector('[ng-controller="inventoryController"] [ng-src="link.com/link/here"]');

Add an id to a dynamically created element

I'm trying to add an id to an element that I create dynamically using javascripts' document.createElement() method. Basically I want to create an iframe in my html document and at the same time give that newly created element an id.
Here's my code so far. I've figured out how to put the element in the DOM and all that, i just need the id.
function build(content){
var newIframe = document.createElement("iframe");
var newContent = document.createTextNode("Hello World!");
newIframe.appendChild(newContent);
var element = document.getElementById("container");
document.body.insertBefore(newIframe, element);
document.getElementsByTagName("iframe").id = "active";
};
As you can probably see, I have tried to give it an id at the very end. Problem is, it doesn't work.
So if anyone has any idea of what is wrong here, or an alternative way of doing what I want to do, please feel free to express yourself. Many thanks!
Just add an attribute (id is an attribute) to that element directly, like this:
var newIframe = document.createElement("iframe");
newIframe.id = 'active';
... although it looks quite strange to have id equal to active (too generic for a unique identifier).
Your current approach doesn't work because document.getElementsByTagName("iframe") returns a collection of elements - NodeList or HTMLCollection (it's browser-dependant). While you can assign a value to its id property, it won't do what you mean to. To make it work, you can adjust it this way:
document.getElementsByTagName("iframe")[0].id = "active";
... but, as shown above, there's a better way.
newIFrame.setAttribute("id", "something");

JS select child of this with specific class

I am writing a GreaseMonkey script that goes through a page with various elements and each element has text and a button. It uses document.getElementsByClassName to find the parent elements, and it has a for loop to do something to each parent element. In this loop, I need to select a child node with a specific class and find its text value (innerHTML). I can't figure out how to select the child with a specific class of this element.
You'll want to grab the currently iterated element and use querySelector()
For example:
var elements = document.getElementsByClassName('class');
for (var i = 0, len = elements.length; i < len; i++) {
var child = elements[i].querySelector('.class_of_desired_element');
//do stuff with child
}
Note the dot before the class name in querySelector as it works similar to jQuery.
Try querySelectorAll(), which you can use to find elements within the current element.
var parent = document.getElementsByClassName('parentClass'),
parent[0].querySelectorAll('.childClass');
Depending on exactly what you are looking to do, you could also skip selecting the parent, if you don't explicitly need a reference to it.
document.querySelectorAll('.parentClass .childClass');
https://developer.mozilla.org/en-US/docs/Web/API/Element.querySelectorAll
You can use
var yourelement = document.getElementsByClass("");
var i = yourelement.nextSibling;
var e = i.nextSibling;
and keep getting the nextSibling of the element till you get it.
However, like #teddy said in the comments, I would suggest you use jQuery. It has a MUCH easier way to do it:
var value = $('.parentClass .childClass').html();

Disable a text area by it's class (not id)

I have 2 text area's that are generated automatically, and I need to use JavaScript to disable both when the page has loaded. The catch is because they are generated automatically I can't give them an ID because they would both have the ID - a big no.
Attempted Javascript:
document.getElementByClassName('option_window-size').disabled=true;
I know this works because if I change getElementbyClassName to ID then it will work if I give the text areas the ID as well. But as I say it needs to work off class. Also it can't work of the Name attribute because that is automatically generated per product and per page...
I have tried this but it just doesn't work and I can't figure out why not because it should as the only thing I have changed is from ID to CLASS
Text Areas
<textarea name="willbeautogenerated" class="option_window-size" cols="40" rows="5">willbeautogenerated</textarea>
Additional note: I have tried to count and assign them different IDs using PHP but it gets far to complex. Also it is only these two that need disabling, thus I can't just disable all text area's on the page.
I know this works because if I change getElementByClassName to ID then it will work if I give the text areas the ID as well. But as I say it needs to work off class.
getElementsByClassName returns a NodeList rather than a Node itself. You'll have to loop over the list, or if you expect just 1 item, choose index 0.
var nodes = document.getElementsByClassName("option_window-size"),
i = 0, e;
while (e = nodes[i++]) e.disabled = true;
jQuery makes this pretty simple:
$(".selector").prop("disabled", true);
ALTHOUGH! It should be noted that this note appears on the man pages for $.prop() and $.attr():
Note: Attempting to change the type property (or attribute) of an input element created via HTML or already in an HTML document will result in an error being thrown by Internet Explorer 6, 7, or 8.
This doesn't apply directly to your question, but you are changing prop/attrs on an input element, so be aware.
But it's still possible with plain old JS:
var els = document.getElementsByClassName("selector"); // note: Elements, not Element
for(var e = 0; e < els.length; e++)
{
els[e].disabled = true;
}
getElementsByClassName returns an NodeList, you just have to iterate over each element within.
You can use class selector,
$('.option_window').attr('disabled', true);
OR
$('.option_window')[0].disabled = true;
With Jquery you can do:
//make sure to use .prop() and not .attr() when setting properties of an element
$('.option_window').prop('disabled', true);
Disable textarea using jQuery:
$('.option_window-size').attr('disabled', true);
your missing a s in elements and the index where the element is like [0], for the first element.
document.getElementsByClassName('option_window-size')[0].disabled=true;
or
document.getElementsByName('willbeautogenerated')[0].disabled=true;
Disabel texarea using .prop() methode in jquery...
$('.option_window-size').prop('disabled', true);
You can use CSS:
.option_window-size{display:none;}

How to get attributes of container in jquery?

How can I get attributes values from an container using jquery ?
For example:
I have container div as:
<div id = "zone-2fPromotion-2f" class = "promotion">
here how can I get attribute id value using jquery and than how can I trim the value to get component information ?
update : how can i get attribute values ?
UPDATE: If I have multiple components on page with same div information than how would I know what attribute value is for which component ?
Thanks.
First, that seems to be a ridiculously long ID -- I'm sure it could be made much shorter while still retaining its uniqueness.
Anyway, on to the answer: First you need a way of accessing your "container" div. Typically, one might use a class or ID to get an element. For example, you could "select" this div with the following call to jQuery:
var container = jQuery('#zone-3a...'); // Fill in ... with really long ID
But, since you're asking how to retrieve the ID, I'm presuming that selecting it via the ID is not an option. You could also select it using the class, although it's not guarenteed to be the only element on the page with that class:
var container = jQuery('.promotion');
There are other ways to narrow down the search, such as:
jQuery('div.promotion');
jQuery('div.promotion:first');
Once you have a reference to your "container", you can retrieve the ID like so:
container.attr('id'); // => zone-3a...
// or:
container[0].id; // => zone-3a...
So assuming your div looks like this.
<div id="foo"/>
You could get the ID attribute by using the attr method.
$("div").attr("id);
That assumes that you only have one div on the page. Not really sure what component information you are looking to get?
You read node attributes with the attr() method.
var id = $( '.promotion' ).attr( 'id' );
In terms of parsing that ID for any other arbitrary information, I can't say since it looks like you're using some sort of proprietary format of which I have no knowledge.
loop thru and get all divs with the class promotion and get the id of each...
$('div.promotion').each(function(){
var attr = $(this).attr('id'); // or whatever attribute
});
or single
var myDivClass = $('zone-3a-2f-2f-2fPortal-2fPages-2fHome-2fZones-2fLeft-2f-7ccomponent-3a-2f-2f-2fSpm-2fComponents-2fPromotion-2f').attr('class');
or another single
var myDivID = $('.promotion').attr('id');

Categories