Get innerHtml by data-id - javascript

I have many <li> with specific data-id, want to get innerHtml of first <Div>
For Example on this sample, it would to be: "World"
<li class="dd-item" data-id="1123066248731271" data-slug="" data-new="1" data-deleted="0"><div class="dd-handle">World</div> <span class="button-delete btn btn-danger btn-xs pull-right" title="Delete" data-owner-id="1123066248731271"> <i class="fa fa-times" aria-hidden="true"></i> </span><span class="button-edit btn btn-success btn-xs pull-right" title="Edit" data-owner-id="1123066248731271"><i class="fa fa-pencil" aria-hidden="true"></i></span></li>
This is my code, that doesn't help:
var target = $('[data-id="1123066248731271"]');
alert(target.firstChild.innerHTML);

document.querySelector('[data-id="1123066248731271"]').textContent

Maybe this is what you need?
Being a jquery element, you can use find() method to find all the div elements inside him, with first(), you get the first element, finally, with html(), you get its content.
var target = $('[data-id="1123066248731271"]');
alert(target.find('div').first().html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="dd-item" data-id="1123066248731271" data-slug="" data-new="1" data-deleted="0"><div class="dd-handle">World</div> <span class="button-delete btn btn-danger btn-xs pull-right" title="Delete" data-owner-id="1123066248731271"> <i class="fa fa-times" aria-hidden="true"></i> </span><span class="button-edit btn btn-success btn-xs pull-right" title="Edit" data-owner-id="1123066248731271"><i class="fa fa-pencil" aria-hidden="true"></i></span></li>

first problem $('[data-id="1123066248731271"]') returned a object of all elements with [data-id="1123066248731271"]. for target the first element, you need add [0] after : $('[data-id="1123066248731271"]')[0]
now if you want target the div element you need specify div into $ like: $('[data-id="1123066248731271"] div')[0]. Now you got the first div and you can get innerHTML with : target.innerHTML
The full code :
var target = $('[data-id="1123066248731271"] div')[0];
alert(target.innerHTML);
and without Jquery ( more simply i think ) :
var target = document.querySelector('[data-id="1123066248731271"] div');
alert(target.innerHTML);

Perhaps you want to use firstElementChild instead of firstChild?
Or you could use the CSS selector [data-id="1123066248731271"] > div:first-child:
var target = $('[data-id="1123066248731271"] > div:first-child');
alert(target.innerHTML);
Edit:
I noticed a translation error. I don't use jQuery myself, so instead of $ I used document.querySelector. But the behavior of $ corresponds to document.querySelectorAll instead. Sorry...
This should work fine:
var target = $('[data-id="1123066248731271"] > div:first-child')[0];
alert(target.innerHTML);
or this:
var target = document.querySelector('[data-id="1123066248731271"] > div:first-child');
alert(target.innerHTML);
As a non-jQuery user, I personally prefer the latter.

Related

How to change href of a button without ID

I'm trying to change the href on this element:
"<button onclick="smoothscroll()" class="btn btn-white btn-small" href="#contacto">blah blah <i class="fas fa-chevron-right"></i></button>"
It doesn't have an ID so I tried like this:
document.getElementsByClassName('btn btn-white btn-small')[0].href="https://www.mysite.cl/#"
But it doesn't seem to work.. any ideas? I have other element that works just like I want this button to work:
"<button onclick="smoothscroll()" class="btn" href="#">blah blah</button>"
But I also tried this:
document.getElementsByClassName('btn btn-white btn-small')[0].href="#"
And it doesn't work either
It is not advised to use href as attribute for html button, use this instead..
<a href = '#blablabla'>Scroll to bla bla bla </a>
Then add this css property to the page
html {
scroll-behavior: smooth;
}
The above css will automatically cause smooth scrolling each time a user scrolls by clicking a link.
But if you insist
Try this.. Change your buttons to
"<button onclick="smoothscroll(this)" class="btn btn-white btn-small" href="#contacto">blah blah <i class="fas fa-chevron-right"></i></button>"
Then your smoothscroll() function should look like..
function smoothscroll(button){
button.setAttribute('href', 'Your new link');
}
If you already know what the href is then select it using that.
Since href is not standard to a button Element, to update the href attribute, use setAttribute.
const button = document.querySelector('button[href="#contacto"]')
button.setAttribute('href', "#");
console.log(button)
<button onclick="smoothscroll()" class="btn btn-white btn-small" href="#contacto">blah blah <i class="fas fa-chevron-right"></i></button>
If you have control of the html, then you should look to change the button to an a element instead.

jQuery replace HTML in string

I want to replace following HTML string:
</p><span onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">XXX</span><p><br></p>
with:
</p><button onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">YYY</button><p><br></p>
using jQuery. I have tried .replace() function, but its not working for some strange reason.
try give span an ID and
You can do:
$("#yourid").text("YYY");
or
$("#yourID").html("testing <b>YYY</b>");
Here you go with a solution https://jsfiddle.net/bqfv5fge/1/
var span = $('span:contains("XXX")');
span.after('<button>YYY</button>');
$(span[0].attributes).each(function() {
$('button:contains("YYY")').prop(this.nodeName, this.nodeValue);
});
span.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">XXX</span><p>
test paragraph
</p>
Use jQuery contains to get the target element.
Reference Document: https://api.jquery.com/contains-selector/
First get the reference of span element, then add button next to span using jQuery after.
Then attach all the attribute to the button and then remove span.
Try this, but better to add an ID for selector.
$(document).ready(function(){
$('span').click(function(){
$(this).text('YYY') or $(this).html('YYY');
})
})
var attr ='';
$("span").each(function(){
$.each(this.attributes,function(){
attr += this.name+'="'+this.value+'"';
});
});
$("span").replaceWith('<button '+attr+'>'+$('span').text()+'</button>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span onclick="alert(event)" class="btn btn-sm btn-success xyz" contenteditable="false">XXX</span>
https://jsfiddle.net/s0bv09gm/.
If you just want to replace "span" with "button" tag:
$(document).ready(function(){
var x = '</p><span onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">XXX</span><p><br></p>';
alert(x.replace(/span/g,"button"));
});
https://jsfiddle.net/L26fvfvL/
If you want to replace XXX with YYY:
HTML Code:
<span onclick="alert(event)" class="btn btn-sm btn-success" contenteditable="false">XXX</span>
JQuery Code:
$(document).ready(function(){
var x = $("span");
x.html(x.html().replace("XXX","YYY"));
})
https://jsfiddle.net/f7qsa6kw/
If you want to do both the things, apply the second step and then first step.

On dropdown element click its icon disappears

This code will replace what is shown inside <button></button> with selected icon from dropdown list.
This works good, only problem is that after clicking on selected element, icon inside that element will for some reason disappear? Why does this happen? I want <li> to be unchanged
http://codepen.io/filaret/pen/PGJEAL
HTML:
<div class="input-group-btn">
<button type="button" class="btn" data-toggle="dropdown">
<i class="fa fa-book"></i>
</button>
<ul class="dropdown-menu">
<li><i class="fa fa-book"></i> Something 111</li>
<li><i class="fa fa-newspaper-o"></i> Something 2222</li>
</ul>
</div>
jQuery:
var $selectWrapper = $('.input-group-btn');
$selectWrapper.find(".dropdown-menu li").click(function() {
// Get <i class="fa"></i>
var $selectedIcon = $(this).find('.fa');
// Put it inside <button></button>
$selectWrapper.find(".btn").html($selectedIcon);
});
You need to clone the icon using clone() like following
var $selectedIcon = $(this).find('.fa').clone();
instead of
var $selectedIcon = $(this).find('.fa');
UPDATED CODEPEN
Otherwise since you have i tag in dropdown and button tag and that only class change, why don't you just copy the class, it's more efficient, faster and easy to understand in your code.
jQuery(document).ready(function($) {
"use strict";
var $selectWrapper = $('.input-group-btn');
var $buttonIcon = $('.btn i');
$selectWrapper.find(".dropdown-menu li").click(function() {
// Get <i class="fa"></i>
var $selectedIcon = $(this).find('.fa');
// get icon classes
var classes = $selectedIcon.attr("class");
// Put the class in the button i tag
$buttonIcon.attr('class', classes);
});
});
See code pen: http://codepen.io/anon/pen/ORxQPZ

How to change html inside a span

I want to change the content of a span in my form
HTML:
<form action="javascript:submit()" id="form" class="panel_frame">
<label>Origin:</label>
<div class="input-group" id="input-group">
<input type="text" id="origin" name="origin" class="form-control">
<span class="input-group-btn">
<button id="btn-default" class="btn btn-default" type="button">
<span class="glyphicon glyphicon-pushpin" aria-hidden="true"></span>
</button>
</span>
</div>
What I want change is che content of <span class="input-group-btn"> with
<button id="btn-default" class="btn btn-default" type="button">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
So what change is: the icon pushpin to remove and the action useCurrentPosition to clearPosition.
I' using jquery and despite I've read other answer about similar question on Stack like: How can I change the text inside my <span> with jQuery? and how to set a value for a span using JQuery I haven't solved the issue.
I tried:
$("#input-group span").html('
<button id="btn-default" class="btn btn-default" type="button" onclick="br_bus.useCurrentPosition()">
<span class="glyphicon glyphicon-pushpin" aria-hidden="true"></span>
</button>
');
,giving an id to the span and also modify the full div, but none solved my problem.
What am I missing?
Here's a way to overcome the problem of changing the onclick attribute, which is bad practice, without storing a Global var, and using jQuery delegation (learn to use it, it's really good):
$(document).on('click','.btn', positionChange); // Give that button an id on his own and replace '.btn' with '#newId'
// Not using an anonymous function makes it easire to Debug
function positionChange(){
var $btn = $(this), // Caching jQuery elements is good practice
$span = $btn.find('span'), // Just caching
pushpinApplied = $span.hasClass('glyphicon-pushpin'); // Check which icon is applied
( pushpinApplied ) ? useCurrentPosition() : clearPosition();
$span.toggleClass( 'glyphicon-pushpin glyphicon-remove' );
}
Rather than changing the function called in the onclick attribute I suggest having a flag in one function to define the logic it should follow.
For example:
function positionChange(this){
var $this = $(this);
if(!$this.data("currentpositionused")){
//useCurrentPosition() code here
$this.data("currentpositionused", true);
}
else {
//clearPosition() code here
$this.data("currentpositionused", false);
}
Then change your HTML to:
<button class="btn btn-default" type="button" onclick="positionChange(this)">
If you want to change only the onclick attribute of the button inside the particular span you can use the following in your script.,
$(document).ready(function(){
$("span.input-group-btn button").attr("onclick","clearPosition()");
});
EDIT
$(document).ready(function(){
$("span.input-group-btn button").attr("onclick","clearPosition()");
$("span.input-group-btn button span").attr("class","Your_class");
});
And also learn about how to change/add/remove attribute values....
Try this:
$("span.input-group-btn").html('<button class="btn btn-default" type="button" onclick="clearPosition()">
<span class="glyphicon glyphicon-pushpin" aria-hidden="true"></span>
</button>');
Is it like This ?
how to change onclick event with jquery?
$("#id").attr("onclick","new_function_name()");
jquery change class name
$("#td_id").attr('class', 'newClass');
If you want to add a class, use .addclass() instead, like this:
$("#td_id").addClass('newClass');

Javascript/JQuery to create a div -Simple Way

I have this code in a div:
<div class="user_event my_background">
<%= image_tag("events_pics/boom.png", :class=> 'event_pic_small') %>
<h6 class="event_info">Event_1: Frame: 974</h6>
<a class="btn btn-mini btn-danger pull-right " href="#"><i class="icon-remove"></i></a>
</div>
and I want this to be appended into an other element each time I click on a button. Anyway the main question is, Is there an easy way to create the above div using javascript? for example a function that takes that as an argument and creates it? Thanks
This simple Jquery function will set the html inside the element selected to whatever you want.
$("SomeElement").html("<div class='user_event my_background'>...</div>")
Just specify the element you want to add the html to and the rest of you html as the argument and you are good to go. Hope that helps.
If you can use jQuery then
$(".user_event").clone().appendTo("#MyTargetElement");
Edit:
Instead of creating a the div again and again, I'd recommend that you keep it hidden in some element and get it using that hidden element's id and append it to your target element.
<div id="myhiddenelement" style="display:none;">
<div class="user_event my_background">
<%= image_tag("events_pics/boom.png", :class=> 'event_pic_small') %>
<h6 class="event_info">Event_1: Frame: 974</h6>
<a class="btn btn-mini btn-danger pull-right " href="#"><i class="icon-remove"></i></a>
</div>
</div>
jQuery
("#MyTargetElement").append($("#myhiddenelement").html());
Use this script:
$("body").prepend('<div>').addClass("user_event").addClass("my_background");
function addElement()
{
$(".user_event.my_background").append('<h6 class="event_info">Event_1: Frame: 974</h6>');
$(".user_event.my_background").append('<a class="btn btn-mini btn-danger pull-right " href="#"><i class="icon-remove"></i></a>');
}
Hope this helps! :)
function append_to_what(id)//id can be any css3 selector
{var div=document.createElement('div');
div.innerHTML='<%= image_tag("events_pics/boom.png", :class=> "event_pic_small") %><h6 class="event_info">Event_1: Frame: 974</h6><a class="btn btn-mini btn-danger pull-right " href="#"><i class="icon-remove"></i></a>';
'
div.className='user_event my_background';
document.querySelector(id).appendChild(div);
}
You may want to check Jquery where you can access a div using class name.

Categories

Resources