jquery or native can't get element by its ID - javascript

So, in a page there is a div with id #SCPcustomOptionsDiv. I want to move that div to a right place where it should be.
I tried using jQuery as well as native javascript, but can't get this to work. When i try to run the script using debugger, the result is null. here is the script.
jQuery('#SCPCustomOptionsDiv') // return []
document.getElementById('SCPCustomOptionsDiv') // return null
and here is some snippet of the source
<span style="display:none;" class="scp-please-wait"><img src="http://optimallyorganic.webmate.co/skin/frontend/base/default/images/scp-ajax-loader.1413318518.gif" class="v-middle" alt="" /> Loading... </span>
<div id="SCPcustomOptionsDiv"></div>
</fieldset>
<script type="text/javascript">
$$('#product-options-wrapper dl').each(function(label) {
label.addClassName('last');
});
</script>
is camelcase id matter when selecting the div using javascript?

The C in SCPcustomOptionsDiv is lowercase in your HTML and uppercase in your script. IDs are case-sensitive.
SCPcustomOptionsDiv
^
vs.
SCPCustomOptionsDiv
^

Use SCPcustomOptionsDiv in your script not SCPCustomOptionsDiv
jQuery('#SCPcustomOptionsDiv')
document.getElementById('SCPcustomOptionsDiv')

Related

Get a part of string from a page source code (information is present in HTML)

How can I look for a keyword in a HTML source code and get a value from the code using Pure JS. There are multiple code tags and I am looking to extract the value 12345 and it can be in any <code> block which doesn't have a unique ID or class. The keyword (word to find in any code tag) to find would be "THIS_IS_WHAT_IAM_LOOKING_FOR".
Example:
HTML source code:
<html>
<body>
(some HTML goes here)
<code style="display: none">
wlkdw,dmnewf4oi4j4f4knkf4kjfkfjk;fefiekf;flegelgjelkghjreg;THIS_IS_WHAT_IAM_LOOKING_FOR12345,95849;fefjefefmdl;fljegflegc;evev;evk;evke;v;evirvrkvjrkvuve;vkev;ejv;
</code>
<code style="display: none">
fffffffffffekjfekfjekfjrgkrgkjkthjtkhjtkhjtkhjkthp;gkrg2;4l3lgfrgrgkrg9;fefjefefmdl;fljegfleg w;c;evev;evk;evke;v;evirvrkvjrkvuve;vkev;ejv;
</code>
</body>
</html>
You can use split() to get the part of the string you are interested in, for instance, in your case, i assume you have the mentioned text before the value and a comma after:
const d0 = htmlCode.split('THIS_IS_WHAT_IAM_LOOKING_FOR')[1] // After this text
.split(',')[0]; // Before this
console.log(d0);
Example working in stackBlitz
https://stackblitz.com/edit/js-hqqvrl?file=index.js
There are probably more elegant ways to do this, but this one should work.

How to edit an element attribute within the html through Selenium and Python?

So my problem is that i need to edit this image source in selenium, but it doesn't have id or class.
<div id="mbr-content">
<div class="nope" some random stuff>
<script>
</script>
<div class="mbr-image-container">
<div class="mbr-image-wrapper">
<div class="mbr-image">
<img src="this source need to modify" alt="app_image">
</div>
</div>
</div>
#Html continues here
I just in some reason cant figure this one out.
I know that I need to use this command but not sure what shut I putt inside as script.
driver.execute_script("something here")
Using python-3.7
The javascript required to set the src attribute of your <img> element is:
document.querySelector(".mbr-image > img").src="whatver you want";
So, you can try below solution:
js = 'document.querySelector(".mbr-image > img").src="whatver you want";'
driver.execute_script(js)
As per the HTML you have shared to edit the src attribute of the desired element you can use the following solution:
element = driver.find_element_by_xpath("//div[#class='mbr-image-container']/div[#class='mbr-image-wrapper']/div[#class='mbr-image']/img[#alt='app_image']")
driver.execute_script("arguments[0].setAttribute('src','something here')", element)

how to get div content by role javascript

I'm trying to get feed content from facebook dom.
<div role="feed">
so i did that:
querySelectorAll($("div[role='feed']"))
like this:
get div by role
but it returns undifend result.
I tried some more similar way but still get undifend.
It is possible to get this data?
thanks
Please remove $. It's not needed and might throw an undefined error. Are you running after the page has loaded? Are you using .innerHTML to get the HTML contents? This works for me:
<div role="feed">Hello</div>
<script>
console.log(document.querySelector('div[role="feed"]').innerHTML);
</script>
In case, if you aren't running after your page has loaded, put your code inside onload event of window object.
You should change your code this way:
<script>
// Loading script before element.
window.onload = function () {
console.log(document.querySelector('div[role="feed"]').innerHTML);
}
</script>
<div role="feed">Hello</div>
This works if you are loading script before element.
You are mixing JavaScript and jQuery.
You don't need $() to do that with .querySelectorAll()
You don't need .querySelectorAll() to do that with $()
You can do any of the following to select the div with role="feed":
let divs_js = document.querySelectorAll("div[role='feed']");
console.log('Elements matched:', divs_js.length);
let divs_jq = $("div[role='feed']");
console.log('Elements matched:', divs_jq.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="feed"></div>
<div role="not-feed"></div>
<div role="feed"></div>
<div role="feed"></div>
<div role="not-feed"></div>
⋅
⋅
⋅
Here is an example of what you can do to get the content, then:
console.log("Using JS:");
let divs_js = document.querySelectorAll("div[role='feed']");
divs_js.forEach(function(elm){
console.log(elm.innerHTML); // or .innerText, according to your needs
});
// ----------------------
console.log("---------");
console.log("Using jQ:");
let divs_jq = $("div[role='feed']");
$(divs_jq).each(function(){
console.log($(this).html()); // or .text(), according to your needs
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="feed">feed 1</div>
<div role="not-feed">not feed 1</div>
<div role="feed">feed 2</div>
<div role="feed">feed 3</div>
<div role="not-feed">not feed 2</div>
Hope it helps.
With jQuery you don't need querySelectorAll() to get the DOM you can achieve this with $("div[role='feed']"). Since you are using querySelectorAll(), it accept string which must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. Since you are using wrong syntax, it returns undefined.
And you need text() function to get content of div in jQuery. text() get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
console.log($("div[role='feed']").text());
console.log($("div[role='feed']"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="feed">
so i did that:
</div>

Problems with getElementById with jquery load

I have a page, showlist.php, which loads a set of results from a recordset. There is a search field which returns results using jquery load. This works fine for one word, but not if there is more than one word in the search query. Can anybody show how to get this to work for any search query? Must be some basic error but googling around has not helped.
Key elements of showlist.php:-
<div id="contentarea">
<script type="text/javascript">
function contentloader(url){
$("#contentarea").load(url);
}
</script>
<input name="search" type="text" id="inputsearch"/>
<a onclick="contentloader('showlist.php?search='+document.getElementById('inputsearch').value+'')">Search</a>
</div>
You need to HTML encode the result of document.getElementById('inputsearch').value so that all the works are passes to the server.
See:
HTML-encoding lost when attribute read from input field
Encode URL in JavaScript?
and links therein.
You need to call encodeURIComponent with the value to correctly format the query/search term:
<a onclick="contentloader('showlist.php?search='+encodeURIComponent(document.getElementById('inputsearch').value)+'')">Search</a>
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
type abc%20xyz in the box. if that works, maybe you need to urlencode the value.
You can use onClick listener, since you are already using jQuery. I think it is a better than using onClick attribute.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<div id="contentarea">
<input name="search" type="text" id="inputsearch"/>
<a id="search">Search</a>
<script type="text/javascript">
$( document ).ready(function (){ // when document ready
$("#search").click(function(){ // add a click listner
$("#contentarea").load(
encodeURI($('#inputsearch').val()) // encode input string
);
}
);
})
</script>
</div>

Dynamically generated script not working

I have a contenteditable div where you type javascript which gets outputted into an empty script tag.
<div contenteditable="true" id="script-generator"></div>
<div id="save-script">Save</div>
<script type="text/shorthand" id="script">
</script>
So you write your script in the div, click save and I have some JS which gets the html of the contenteditable div and adds it to an empty script tag.
$('#save-script').click(function() {
var script = $('#script-generator').html();
$('#script').html(script);
});
So far this works. But the generated script has no effect. The browser must not recognise the script because it wasn't there on page load? How do I make the script take effect without reloading the page?
Note: The type/shortand on the script is because I'm using a plugin which converts shortand words into actual Javascript. So the user would just need to write shorthand into the contenteditable div, and the plugin would convert that to JS. This might be adding to the problem?
I don't think it works to modify an existing <script> element. If you want the script to be executed you need to add a new element.
$('#save-script').click(function() {
var script = $('#script-generator').html();
$("#script").text(script);
ShortHand.parseScripts();
});
Correct - you need to create the script tag to have it execute after load.
$('head').append($('<script />', {html: script}));
...which means you can remove your empty script tag.
I have set up a test that's similar to what you have been looking for. Take a look and see if that helps.
Working Demo
Test code:
<div id="script" style="display:none">
alert(4+4);
</div>
<input id="sLoad" type="button" value="Load/Execute Script" />
$('#sLoad').click(function(){
//You may want to append to the head
$('<script/>').append( $('#script').html() ).appendTo('#script');
});

Categories