Javascript: check for ::after in element - javascript

I have a very simple element:
How can I check if this element contains the ::after using Javascript?
(I have the element using document.getElementsByTagName('h2')[0])
I don't know how the thing works, and I don't need to know, I just need the code to see if it exists...
In some cases the element looks like this:
I need to be able to detect both cases, if possible!

It would be something like this:
var pre = onload; // assign previous onload if any
onload = function(){ // onload wrapper start
if(pre)pre(); // execute previous onload in the new onload
var doc = document, h2a = doc.getElementsByTagName('h2');
var afterIn = [], afterOut = [];
for(var i=0,l=h2a.length; i<l; i++){
var h2 = h2a[i];
if(h2.value.match(/\:\:after/)){
afterIn.push(h2);
}
else{
afterOut.push(h2);
}
}
for(var i=0,l=afterIn.length; i<l; i++){
console.log(afterIn[i].value);
}
for(var i=0,l=afterOut.length; i<l; i++){
console.log(afterOut[i].value);
}
} // onload wrapper end

Check this link, explains how to use it in plain JavaScript (might only work in newer browsers): http://davidwalsh.name/pseudo-element
Edit: if you're looking to edit what the content of the :after is, reference this SO question: Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery

Related

Issue with addEventListener & target clic in my website

I'm playing around with HTML, CSS & JavaScript but I'm not very good. I'm trying the following:
<script type="text/javascript">
var tab = document.getElementsByClassName("MYCLASS");
for(var i = 0, j=tab.length; i<j; i++){
tab[i].addEventListener('click', afficher,false);
}
function afficher(){
alert(this.class);
}
</script>
Attaching the click listener on all my .MYCLASS divs is working. However, on Google Chrome in the alert window it throws me undefined instead of .MYCLASS.
So I tried this code as alternative:
function afficher(e){
var target = e.target || e.srcElement;
var $target = $(e.currentTarget);
alert(target.class);
}
But the result is exactly the same. Any help is appreciated, thank you!
This is because there's no property defined for a html DOM object named class.
If you want to get the class value, you should use this.className.
So your function should look like this:
function afficher(){
alert(this.className);
}
You can just use a simple 'for in' loop, but you need to be sure that you are appending events to only DOM elements. The HTML list that is returned by getElementsByClassName() isn't only returning DOM elements.
var tab = document.getElementsByClassName("MYCLASS");
for(var i in tab){
// you need this check to filter anything that isn't a DOM element
if(typeof tab[i] ==="object"){
tab[i].addEventListener('click', afficher,false);
}
}
function afficher(){
alert(this.className);
}

Hide H1 Element using JavaScript

I want to hide the <h1> element using plain javascript, not jQuery, without adding id="whatever" or class="whatever" to the tag. Is this possible?
Why can't I just add id="whatever" to the tag?
I'm using a UIButton in xCode that when clicked, it injects javascript into a UIWebView. Inside that UIWebView is a H1 element that is on a website that I do not have access to to add <h1 id="whatever">. I hope it makes sense.
document.getElementsByTagName('h1')[0].style.display = 'none';
You can use getElementsByTagName method:
var h = context.getElementsByTagName('h1');
for (var i = h.length; i--; ) {
h[i].style.display = 'none';
}
Where context is document or more specific parent node you want to search your headers within.
However there is better solution. You could add specific class to some parent node and hide child headers with CSS:
.without-headers h1 {display: none;}
Use getElementsByTagName to hide the first h1 on your page:
document.getElementsByTagName("h1")[0].style.display = "none";
// ^ index 0, so that's the first `h` that's found.
Or to hide them all:
var headers = document.getElementsByTagName("h1");
for (var i = 0, l = headers.length; i < l; i++; ) {
headers[i].style.display = "none";
}
Or even better yet, if you can modify the CSS:
h1{
display:none;
}
For the JavaScript solutions, please keep in mind that they will only work when the DOM has been loaded.
Add a domready event listener, like this:
window.addEvent('domready', function() {
// modify your DOM here.
});
you can use getElementsByTagName
document.getElementsByTagName("h1")
But it will access all h1 elements, so to be more specific access it by index like this
document.getElementsByTagName("h1")[0].style.display = "none";
just small change in dfsq's code
var h = document.getElementsByTagName('h1');
for (var i =0; i<h.length; i++) {
document.getElementsByTagName('h1').item(i).style.display = 'none';
}

How can access bunch of <li>?

I have a list of texts and I want to change their innerHTML. how can I do that by javascript if I have thousands of li tag (whose data come from database)?
<div>
<ul>
<li>a</li>
<li>as</li>
<li>asd</li>
<li>asds</li>
<li>asdsa</li>
<li>asdsad</li>
<li>asdsadz</li>
<li>asdsadzc</li>
....
.....
</ul>
</div>
-Thanks.
Update
JS code being used:
function a(){
var parent = document.getElementById("z");
var i = 0;
for(i = 0; i <= parent.children.length; i++){
if(parent.children[i].tagName == "LI"){
if(i%2!=0){
parent.children[i].innerHTML="ok";
}
}
}
}
document.onload=a(); // this didn't work. so I called the function in body tag instead of that.
<body onload="a();">
Have you tried using getElementsByTagName ? Sonds like it would help you find the elements you're trying to work with.
Edit
If you can give an Id to the UL element that holds the li's you're trying to process, you could do something like this:
var parent = document.getElementById("yourID");
var i = 0;
for(i = 0; i < parent.children.length; i++){
if(parent.children[i].tagName == "LI") {
//do what you want...
}
}
EDit 2
You have to change the last line on your script:
document.onload=a();
With this one: window.onload=a;
That'll get your function to execute on the onLoad event. Note that there might be some crossbrowser incompatibility, I would suggest researching a bit on how to execute functions on the onload event on a crossbrowser manner, or just adding this to your body tag:
<body onload="a();">
Given the - not so far fetched - precondition you wish to use jQuery, you can select them and iterate over them with "each".
$("li").each(
function() { $(this).html("changed content"); }
);
If you are not using jQuery, using a js-library that helps you out with the quircky dom is probably not a bad idea...
The general idea
Select nodes
Iterate and change html
is always the same.

Using Javascript, what is the method to get an element, based on the text between the opening and closing tags?

I'm a beginner, and couldn't find the answer after searching.
In my example, I'm looking for an
some text here
I'd want to find this particular element, so I can do stuff with it.
Edit: The only thing I know that's unique about the element for sure, is the text "some text here", that's why I want to find it based on that.
Put id on the element:
<a href="bla" onclick="dah" id='myEl'>some text here</a>
From javascript:
var myEl = document.getElementById('myEl') // gives the element
You can also use psuedo selector :contains, with the jQuery library.
Example 2
$('div:contains("test")').css('background-color', 'red');​
http://jsfiddle.net/9z5du/
Example 2
<script>
$("div:contains('John')").css("text-decoration", "underline");
</script>
If you know that the element is a link, you can first call getElementsByTagName [docs] to narrow down your search:
var elements = document.getElementsByTagName('a');
Then you have to iterate over the elements and test which one contains the next you are looking for:
var element = null;
for(var i = 0, l = elements.length; i < l; i++) {
if(elements[i].innerHTML === 'some text here') {
// found the element
element = elements[i];
break;
}
}
if(element) {
// found the element, lets do something awesome with it
}
There are multiple ways to get the content of an element, using Node#innerText (IE) or Node#textContent (W3C) is another option. You might have to trim the text first before you compare it.
If the HTML is as shown in your post,
if(elements[i].firstChild || elements[i].firstChild.nodeValue)
is even more elegant.
The MDN documentation about the DOM might be helpful.
If you can modify the HTML then adding an ID and using getElementById would be the better option.
Try this
function getit()
{
var elems = document.getElementsByTagName('a');
for(var i=0; i<elems.length; i++)
{
var text = elems[i].childNodes[0] != null ? elems[i].childNodes[0].nodeValue : '';
if(text == "some text here")
doSomethingWith(elems[i]);
}
}

get element after page loads

how do i call a function to count the number of divs with an id of 'd1' after the page loads. right now i have it in my section but doesnt that execute the script before anything in the loads? because it works if i put the code below the div tags...
Firstly there should be at most one because IDs aren't meant to be repeated.
Second, in straight Javascript you can call getElementById() to verify it exists or getElementsByTagName() to loop through all the divs and count the number that match your criteria.
var elem = document.getElementById("d1");
if (elem) {
// it exists
}
or
var divs = document.getElementsByTagName("div");
var count = 0;
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
if (div.id == "d1") {
count++;
}
}
But I can't guarantee the correct behaviour of this because like I said, IDs are meant to be unique and when they're not behaviour is undefined.
Use jQuery's document.ready() or hook up to the onLoad event.
well an ID should be unique so the answer should be one.
you can use <body onload='myFunc()'> to call a script once the DOM is loaded.
You need to have the function tied to the onload event, like so:
window.onload = function() {
var divElements = document.getElementById("d1");
var divCount = divElements.length;
alert(divCount);
};
For the record, you should only have one div with that ID, as having more than one is invalid and may cause problems.

Categories

Resources