Selecting the visible div from a set of them using their class - javascript

I have only one visible div between a lot of them. How can select it?
Following code works in localhost but not online:
var page_div_visible = $(".gform_page").filter(":visible");
I know that could walk through divs using .each() and select with .is(":visible") but
I would prefer one line solution. Is't possible?
EDIT:
html looks like this:
<div id='gform_page_20_6' class='gform_page' style='display:none;'>
</div>
<div id='gform_page_20_7' class='gform_page' style='display:none;'>
</div>
<div id='gform_page_20_8' class='gform_page' >
</div>
EDIT 2
It was not possible make it works online. This is the final solution:
var page_div_visible;
$(".gform_page").each(function(i){
if ($(this).css("display") !== "none"){
page_div_visible = $(this);
return false;
}
})
Thanks for your support.-

Why don't you just do this?
var page_div_visible = $(".gform_page:visible");
http://jsfiddle.net/JoshuaPack/AtBx3/1/

Which version of jQuery are you using? May be you are also having a conflict with $ or adding classes to divs after your code.
Looking at your comment that it is being interfered by some other js code, kindly try using jQuery instead of $
// at the very beginning of your main JavaScript file
var jQ = jQuery.noConflict();
// at the place where you are doing other stuff with $, like your issue
var page_div_visible = jQ(".gform_page:visible");

Related

Remove any specific html code using javascript

In the past I used Google Developer Console to delete some specific divs on a page. I could do it manually of course but in some cases where the divs where many I had to use the console. I had a single line code that did the job (I found it while searching the internet) but I lost my note.
So how can I delete using javascript any html code (by copy pasting the code).
Something like:
elements = $('<div ... </div>');
elements.remove();
OR
$('<div ... </div>').remove();
Any ideas? I am not an expert in javascript (obviously) and I've been searching stackoverflow for hours without finding anything that works.
UPDATE: I think some people might get confused with my question. Google developer console accepts javascript command lines. So even though I ask for javascript I will use the code on the google developer console.
UPDATE 2 :
Here is an example of a div I need to delete. Keep in mind I want to copy paste the entire code in the javascript code. Not just identify the div.
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
It's the data-entry-status="declined" that makes that div unique so I can't just identify the div using an id selector or a class selector. I need to put the entrire thing there and remove it.
I tried:
$('<div class="entry-status-overlay" data-entry-status="declined"><div class="entry-status-overlay__inner"><span class="entry-status-overlay__title">Declined</span></div></div>').remove();
It didn't remove the div.
Try to search the dom by its outerHTML.
function deleteDomByHtml(html){
html=html.replace(/\s/g,'');
$("*").each(function(){
if(this.outerHTML.replace(/\s/g,'')===html){
$(this).remove();
}
});
}
And try this line on this page:
deleteDomByHtml(`<span class="-img _glyph">Stack Overflow</span>`);
You cannot do by simply pasting the code. That will remove all the div element.
You may need a specific selector like id,class or child to specific parent to remove the element from the dom.
Consider this case the divs have common class but the data-entry-status is different. So you can get the dom using a selector and then check the dataset property.
For demo I have put it inside setTimeout to show the difference. In application you can avoid it
setTimeout(function() {
document.querySelectorAll('.entry-status-overlay').forEach(function(item) {
let getStatus = item.dataset.entryStatus;
if (getStatus === 'declined') {
item.remove()
}
})
}, 2000)
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div class="entry-status-overlay" data-entry-status="accepted">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">accepted</span>
</div>
</div>
Just add any attribute with [] and it will remove the element.
$('[class="entry-status-overlay"]').remove();
/*OR*/
$('[data-entry-status="declined"]').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
function del(){
var h = document.body.outerHTML;
h = h.match('<div>...</div>');
h.length--;
return h;
}
I guess this will work just give it a try... i tried on browser console and it worked, this way you can match the exact you want.
I might as well add my take on this. Try running this in your console and see the question vanish.
// convert the whole page into string
let thePage = document.body.innerHTML,
string = [].map.call( thePage, function(node){
return node.textContent || node.innerText || "";
}).join("");
// I get some string. in this scenario the Question or you can set one yourself
let replacableCode = document.getElementsByClassName('post-layout')[0].innerHTML,
string2 = [].map.call( replacableCode, function(node){
return node.textContent || node.innerText || "";
}).join("");
// replace whole page with the removed innerHTML string with blank
document.body.innerHTML = thePage.replace(replacableCode,'');
If you want to identify divs with that particular data attribute, you can use a data-attribute selector. In the example below, I've used a button and click event to make the demo more visual, but in the console the only line you'd need would be:
$('div[data-entry-status="declined"]').remove();
$(function() {
$("#testbutton").click(function() {
$('div[data-entry-status="declined"]').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div id="x">Some other div</div>
<button type="button" id="testbutton">Click me to test removing the div</button>
See https://api.jquery.com/category/selectors/attribute-selectors/ for documentation of attribute selectors.
P.S. Your idea to paste some raw HTML into the jQuery constructor and then execute "remove" on it cannot work - you're telling jQuery to create an object based on a HTML string, which is, as far as it's concerned, a new set of HTML. It does not try to match that to something existing on the page, even if that exact HTML is in the DOM somewhere, it pays it no attention. It treats what you just gave it as being totally independent. So then when you run .remove() on that new HTML...that HTML was never added to the page, so it cannot be removed. Therefore .remove() has no effect in that situation.

Is it possible to find all comments in a HTML document and wrap them in a div?

I'm working with a third party system that renders content into a html document like this:
<!-- componentID: 1234 -->
<div class="some-class"> .... </div>
<!-- componentID: 1235 -->
<div class="another-class"> .... </div>
So the system renders that componentId into a comment. The system sadly provides no way for me to pass that id as a data attribute. I am currently stuck with this.
Is it possible to find all these comments and wrap them in a div/span where they are sitting in the document? I could then access that string and grab the id with regex.
Thanks
try this, it grabs all comments in html file. if there is no other unrelated comments to your plan, this can do the job.
$(function() {
$("*").contents().filter(function(){
return this.nodeType == 8;
}).each(function(i, e){
alert(e.nodeValue);
});
});
I will post non jQuery solution and much more efficient then traversing the whole DOM tree:
var x = document.evaluate('//comment()', document, null, XPathResult.ANY_TYPE, null),
comment = x.iterateNext();
while (comment) {
alert(comment.textContent);
comment = x.iterateNext();
}
However this solution is not for IE, which doesn't implement document.evaluate methods, that's why be aware and use it only if you don't have to support IE.
Demo: http://jsfiddle.net/z6GU3/
You can get all the comments using a function like this:
var $comments = [];
$("*").contents().filter(function() {
return $(this)[0].nodeName == "#comment";
}).each(function() {
$comments.push($(this));
});
console.log($comments);
http://jsfiddle.net/Whre/Zjj3n/
Unfortunately, I do not understand what you mean by
wrap them in a div/span where they are sitting in the document
If the comment belongs to the next element, you could directly apply it to the element: http://jsfiddle.net/Whre/Zjj3n/3/

Javascript - clearing everything inside a div

I have div:
<div id="socialUserList">
//some content here, htmlTags, text, etc.
</div>
Now, I want everything inside of that div to be wiped out. I am trying this:
$("#socialUserList").innerHTML = '';
But for some reason it doesn't want to work. Why?
The normal JavaScript method:
document.getElementById('socialUserList').innerHTML = '';
In jQuery:
$('#socialUserList').html('');
Pure JavaScript and jQuery go hand in hand, like so:
From pure JavaScript to jQuery:
var socialUserList = document.getElementById('socialUserList');
console.log($(socialUserList).html());
From jQuery to pure JavaScript:
var socialUserList = $('#socialUserList');
console.log(socialUserList[0].innerHTML);
Have you tried:
jQuery('#socialUserList').empty();
Note: You may have also tried this:
jQuery('#socialUserList')[0].innerHTML = '';
Using the [0] will access the DOM object of the first matching element.

Grails rendered content accessing id elements dynamically

AJAX content is being rendered with a remoteLink function inside the form to populate a accordion (just a little background info).
The function attatchEmail(test) which is being called on the double-click of each paragraph content of the JQuery Accordion widget. This is what happens running the function... Screenshot of 1st alert & Screenshot of 2nd alert.
Is it not possible to select the paragraph and get the contents from the paragraph like below?
(I have tried changing .val to .html and .text. I have also tried $('#'+testingID))
_form.GSP
function attatchEmail(test) {
$(document).ready(function()
{
var testingID = test.id;
alert(testingID);
var testingValue = $(testingID).val();
alert(testingValue);
});
};
_contactListAjax.GSP
<g:each in="${contactList}" status = "i" var="contact">
<h3>${contact.contactSurname +', '+ contact.contactForename}</h3>
<div><p id="contact${contact.id}" ondblclick="attatchEmail(this)">${'Email: '+contact.email}</p></div>
</g:each>
Run out of avenues to explore, I'm sure I've done something simple like this before perfectly fine :/
See two screenshots please for better insight, thanks
Well, it looks like you're using jQuery but it also looks like you're not really buying into the jQuery methodology. Mixing behavior with markup is not really considered a good practice these days, especially when using a library like jQuery. I'm not sure of your exact issue but I would recommend changing it to something like the following:
<g:each in="${contactList}" status = "i" var="contact">
<h3>${contact.contactSurname +', '+ contact.contactForename}</h3>
<div><p class="contact-email" data-id="${contact.id}">${'Email: '+contact.email}</p></div>
</g:each>
$(function() {
$("body").on("dblclick", ".contact-email", attachEmail);
});
function attatchEmail(event) {
var $element = $(event.target);
var id = $element.data("id");
};
This should help fix any issues with dynamic rendering because of the way the jQuery on function works.

NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument arg 0 [nsIDOMWindow.getComputedStyle] (Followup)

Ok so I finally figured out which part of my code is causing the exception. You can read the initial post here. The code in the initial post is missing the part which is actually causing the exception (the manual subscription to the viewPortData observable). Apparently, I'm doing it wrong somehow... Here's the code:
self.viewPortData = ko.observable();
self.viewPortData.subscribe(function (newValue) {
var viewPort = $('#metro-view-port');
if (viewPort && newValue) {
self.fadeInOut(viewPort, newValue);
}
});
self.fadeInOut = function (domObject, newContent) {
if (newContent) {
var currentContent = domObject.html();
if (currentContent) {
var wrappedContent = $(currentContent);
wrappedContent.fadeOut(400, function () {
wrappedContent.empty();
domObject.html(newContent).hide().fadeIn(400);
});
} else {
domObject.html(newContent).hide().fadeIn(400);
}
}
};
So where did I go wrong?
The same error occurred to me. The problem was caused because the HTML had comments on it. Something like:
<!-- Some Comment goes here -->
<div>
...
</div>
To fix that, without changing the HTML, you need to wrap the HTML with something else, so you pass only one element to jQuery:
var div = document.createElement( 'div' );
div.innerHTML = nativeHtml;
var $html = $( div );
I created a fiddle using your code from this post and the previous post, and it works as it should.
However, I'm only returning a simple <div> tag to populate the HTML of the metro-view-port <div>.
My best guess is that the HTML that you're returning is the problem.
My advice to you is to first confirm this by reducing the HTML returned to something very simple, and then gradually reintroduce the intended code until you find the problem.
Flip your fadeIn(400) to a show().
It is simpler for jQuery to do the math for.... I think that it can't get computed style of the elements due to some floats inside it or something.
I had the same problem..... but after some research I got to here (DAMMET I LOST THE TAB - it was a jQuery bug report anyway ) and realised what needed to be fiddeled with to fix it.
In my code I swapped out fadeIn() to show() so it isn't to do with the animation
you would have thought that without the animation the problem wouldn't be prevalent either - but it is.
try slideDown(0 if your still after an animation, it might not work but its worth a pop.
This bug was in old versions of jQuery. Try to change .hide() to .css('display', 'none')
According to this jQuery bug, the problem may have to do with newline characters and whitespace text nodes in your HTML. In my case, I was taking a template like this one:
<script id="myTemplate" type="text/template">
<div>
<h2>Important stuff</h2>
</div>
</script>
And parsing it like this:
var currentContent = $.parseHTML($('#myTemplate').html());
So I ended up with a bunch of text nodes representing the newline and whitespace characters in the original HTML template. Probably something similar has happened to you.
To fix this, I stripped out the newlines and whitespaces like so:
$('#myTemplate').html().replace(/\n/g, '').replace(/>\s+</g, '><').trim();
Hope that helps someone!

Categories