Javascript equivalent function from jQuery

$.ajax({
url: 'http://' + window.location.host + '/',
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
    // will loop through 
    var images = $(this).attr("href");

    $('<p></p>').html(images).appendTo('a div of your choice')

 });
}
});

I could not find a way to do the same in javascript, I can make an ajax call like this

request = new XMLHttpRequest();
    request.open('GET', 'http://' + window.location.host + '/', true);

    request.onload = function(files) {
        if (request.status >= 200 && request.status < 400){
            // Success!

            resp = request.responseText;
        } else {
            // We reached our target server, but it returned an error

        }
    };
    request.onerror = function() {
        // There was a connection error of some sort
    };

but how do I get a list of files in a directory?

CSJS and / or SSJS are both responses in order. My main goal is not to use jQuery to accomplish what I want.

+4
source share
2 answers

If you want to go through a:contains(.jpg), as in the jQuery example, it is best to use DocumentFragment and then type .querySelectorAllon it:

var div = document.createElement('div');
div.innerHTML = request.responseText;

// if you want to search using text
var links = div.querySelectorAll('a')
for (i = 0; i < links.length; i++) {
  var link = links[i];
  if (!~link.innerHTML.indexOf('.jpg'))
    continue;
  // found one !
}
// if you want to search using an attribute
var links = div.querySelectorAll("a[href*='.jpg']");
+2
source

<div> ; IE7 :

// $(resp)
var doc = document.createElement('div');
doc.innerHTML = resp;

// .find('a')
var anchors = doc.getElementsByTagName('a'), // get all anchors
container = document.getElementById('some_id');

// .filter(":contains(.jpg)")
for (var i = 0; i < anchors.length; ++i) {
    var contents = anchors[i].textContent || anchors[i].innerText || '';

    if (contents.indexOf('.jpg') != -1) {
        // var images = $(this).attr("href");
        // $('<p></p>').html(images).appendTo
        var para = document.createElement('p'),
        text = document.createTextNode(anchors[i].href); 

        para.appendChild(text);
        container.appendChild(para);
    }
}
+1

Source: https://habr.com/ru/post/1544716/


All Articles