jQuery get sibling using next() returns undefined - javascript

How do you use jQuery's next() method to get the contents of an element's sibling? I am trying to get text associated with a google search result. To this end, I stored links in a variable with $('h3.r a'). Next I added a click handler, which would trigger the code that grabs the page description underneath the link. I expected $(this).next().html() to get contents of the next sibling in the same manner $(this).html() worked. Unfortunately, I was mistaken. Here is the jQuery, any help is really valued
links.click(function() {
var nextElement = $(this).next()
console.log(nextElement.html()) //why doesn't this get contents?
var d = $(this).nextElementSibling
console.log(d)
})
EDIT: so I checked the console and when I logged $(this) I got
{
"0":{
"jQuery311027308429302958161":{
"events":{
"click":[
{
"type":"click",
"origType":"click",
"data":null,
"guid":1,
"namespace":""
}
]
}
}
},
"length":1
}
When I logged $(this).next()
{
"length":0,
"prevObject":{
"0":{
"jQuery311027308429302958161":{
"events":{
"click":[
{
"type":"click",
"origType":"click",
"data":null,
"guid":1,
"namespace":""
}
]
}
}
},
"length":1
}
}

Use this.nextSibling to select next #text node, .textContent to select text of node.

Related

remove div if empty or appendChild

I need that when my div is empty, remove if not, run the appendChild code. I'm not getting the logic right, I think
$(window).on("load", function() {
if ('#leftmenu:empty') {
$('#leftmenu:empty').remove();
} else {
document.querySelector('.iframe-output').appendChild(
document.querySelector('.paddingbox iframe')
}
});
$(window).on("load", function() {
if ($('#leftmenu').html().length == 0) {
$('#leftmenu').remove();
} else {
//do whatever
}
});
I don't know what you want. Please refer enter link description here to find how to check div is empty. Then if not you can add the code you want. Currently, this code is the wrong syntax. You need to fix it like
document.querySelector('.iframe-output').appendChild(
document.querySelector('.paddingbox iframe'));
$( "p:empty" )
//.text( "Was empty!" )
//.css( "margin", "0" )
.remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Has text</p>
<p></p>
<p></p>
<p>Has text</p>
Please Try this
$(document).ready(function() {
if ($('#leftmenu').length==0)
{
$('#leftmenu').remove();
} else {
document.querySelector('.iframe-output').appendChild(
document.querySelector('.paddingbox iframe')
}
});
You've got a couple of errors with your code - you're if statement is only checking a string and not actually if the empty div exists and you have a syntax error on your append (and I'm not sure you can append directly to a collection like that)
Try this (comments to what I have changed)
$(window).on("load", function() {
var $emptyDiv = $('#leftmenu:empty'); // get empty div
if ($emptyDiv.length) { // see if empty div exists
$emptyDiv.remove(); // remove empty div
} else {
$'.iframe-output').append($('.paddingbox iframe')); // you may as well use jquery append as you are using jquery
}
});
:

How to check if a HTML element contains an other one?

I want to check if my title <h3> has the class highlight so I founded How to check if element contains specific class attribute but I'm not sure about how to fit it to my use case because it's not the <h3> which contains the class but the span inside it:
I tried to do this code:
$('.liContainer div h3').each(function(i, obj) {
var contains = false;
String classes = obj.getAttribute("class");
for (String c : classes.split(" ")) {
if (c.equals("highlight")) {
contains = true;
}
}
if(contains){
obj.classList.remove("highlight");
}
});
but I got an error with the actual code:
imports/ui/layout.js:42:13: Unexpected token (42:13)
and it's the line String classes = obj.getAttribute("class");
Could someone help me to make it works ?
[EDIT] with the help of your answer I'm now here:
'click .liContainer div h3': function(e){
if ( $(e.target).find("span").is(".highlight") ) {
console.log("it was highlighted");
$(e.target).find("span").removeClass('highlight');
}
},
and it works so thank you everybody
I hope it will help you
$('.liContainer div h3').each(function(i, obj) {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
**can you just help me to do the action only on the clicked h3?**
If `click` action:
$('.liContainer div h3').click(function() {
if ( $(this).find("span").is(".highlight") ) {
// do something
}
});
I use your code, and change the content of the `each` loop.
You loop each `<h3>` and check if child `<span>` has class `.highlight`, then you do something...
The above Code can also be written as follows:
$('.liContainer div h3').click(function() {
if ( $(this).find("span.highlight") ) {
// do something
}
});
Hope this works fine.
$('h3').filter(function(){
return $(this).find('span.highlight').length != 0;
}) // do something with it
A rough way to know if you don't know have child selector
$('#nameMachine *').hasClass('yourClass'); // either true or false
Since you are using jquery, how about this simple solution:
$('.liContainer div h3 .highlight').removeClass('highlight');
Try using `has` selector as given below code :
$('.liContainer div h3:has(span.highlight)').each(function(){
// code here
});
You may try something like:
if( $("h3", "#nameMachine").has(".highlight") ) {
// do something
}
Or a more specific version:
if( $("> h3", "#nameMachine").has("span.highlight") ) {
// do something
}
$('span.highlight','.liContainer div h3').removeClass('highlight')
Please note that the second css selector is to determine the scope of searching the first css selector.
find() will be searching in all of child element . So if there have wanted class its length will be 1 else length is 0.
$('.liContainer div h3').each(function(i, obj) {
var hasClass = $(obj).find(".highlight");
if (hasClass.length) {
hasClass[0].classList.remove("highlight");
}
});
This will do. hasClass documentation is here
$("#nameMachine h3").hasClass("highlight")
if ($('#parent').find('#child').length) {
}

JavaScript - If checkbox is disabled, add class using jQuery

I'm having a problem with the syntax (or maybe with the selectors) on my code. See the demo.
I tried the following code but the results does nothing.
#1. hasAttribute():
if ($('input[type=checkbox]').hasAttribute("disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#2. is():
if ($('input[type=checkbox]').is("[disabled]")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
// ------------------------------------------------
if ($('input[type=checkbox]').is(":disabled")) {
$(this).closest('.chkbox').addClass("is-disabled");
}
#3. prop():
if ($('input[type=checkbox]').prop("disabled", true)) {
$(this).closest('.chkbox').addClass("is-disabled");
}
So then I think the problem is on the line:
$(this).closest('.chkbox').addClass("is-disabled");
Any idea?
Thanks.
You can use :disabled selector
see here
You're using $(this) without declaring anything. Thats the reason it's not working. It works in the second example because of the .change() function gives the context of the 'thing' (this) that is changing.
This code should work as you desire.
$(function() {
// Grab all inputs with the type checkbox.
var input = $('input[type=checkbox]')
// Check for each of the input fields (i, el stands for index, element)
input.each(function(i, el) {
// Does it have the attribute disabled?
if(el.hasAttribute('disabled')) {
// Add the class 'is-disabled'
$(el).closest('.chkbox').addClass('is-disabled')
}
})
$('input[type=checkbox]').change(function(){
if ($(this).is(":checked")) {
$(this).closest('.chkbox').addClass("is-checked");
} else {
$(this).closest('.chkbox').removeClass("is-checked");
}
});
});

How to check the presence of a DOM element in protractor?

Just want to click the log off link if it exists. No action if that link is not present.
Here is the code:
browser.get(browser.baseUrl + 'login');
var lnkLogOff = element(by.linkText('Log off'));
if (lnkLogOff.isPresent()) lnkLogOff.click();
It appears nothing is wrong. But I got a NoSuchElementError when the link is not on page.
What is the correct way to check the presence of an element in protractor?
You can use isElementPresent():
var locator = by.linkText('Log off');
browser.isElementPresent(locator).then(function (present) {
if (present) {
element(locator).click();
}
});
try this code, looks like you are not waiting for element to be presented.
var waitElementToBeShown = function (elm) {
browser.wait(function () {
return elm.isPresent();
},15000);
browser.wait(function () {
return elm.isDisplayed();
},15000);
};
1st part corresponds for the presents of the element in the DOM,
2nd part corresponds for an ability to click on it

How to hide a div map if "p" tag is empty

I need to hide a div (.map_toogle) if a p-tag contains 'I have no Map', otherwise (p-tag is empty) I want to visible that div (.map_toogle).
I have following code but it always hide that div if p-tag is empty.
$(document).ready(function () {
if($(".right_block p:contains('I have no Map')")) {
$('.map_icon').hide();
}
if($(".right_block p:contains('I have no Map')")) {
$('.map_toogle').hide();
}
if($(".right_block p:contains('I have no Map')")) {
$('#camera_wrap_2').show();
}
if($('.right_block > p').is(':empty')) {
$('.map_toogle').css("display", "block");
}
if($('.right_block > p').is(':empty')) {
$('.map_toogle').css("display", "block");
}
});
Why not:
$(".right_block p").text()!== 'I have no Map' ? $(".map_toggle").show() : $(".map_toggle").hide();
This is a simple if/else statement testing on whether the text within the p explicitly matches the string 'I have no Map' and showing/hiding the map div as a result.
That said, you may want to expand this into a regular full-fat statement as it looks like you're also performing a few other actions:
if($(".right_block p").text()!== 'I have no Map'){
$(".map_toggle").show();
// other actions...
}else{
$(".map_toggle").hide();
// other actions...
}
However..
Generally it is best to code in as accommodating way as possible, what if you change the text indicating there is no map? As such, it may be better to test for the inverse (as long as you know this will be no text at all), and use:
if($(".right_block p").text()){ // ....no text present
You have multiple if checks while you can reduce it this way and check for the length:
$(document).ready(function () {
if($(".right_block p:contains('I have no Map')").length !== 0) {
$('.map_icon, .map_toogle').hide();
$('#camera_wrap_2').show();
}
if($('.right_block > p').text().trim() === '') {
$('.map_toogle').css("display", "block");
}
});
This will do the trick
if($('.right_block p').text()==="I have no Map") {
$('.map_icon').hide();
} else {
$('.map_icon').show();
}
You need to fetch the content using .text() which will return you the text

Categories

Resources